forked from Tacodiva/Motely
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchManager.cs
More file actions
1494 lines (1286 loc) · 52.8 KB
/
SearchManager.cs
File metadata and controls
1494 lines (1286 loc) · 52.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections.Concurrent;
using DuckDB.NET.Data;
using Motely.DuckDB;
using Motely;
using Motely.Executors;
using Motely.Filters;
using System.Text.Json;
using System.Linq;
using Motely.API; // For SearchResult type
namespace Motely.API;
/// <summary>
/// Manages search instances with DuckDB persistence and proper sequential searching
/// Follows BalatroSeedOracle patterns for search management
/// </summary>
public class SearchManager
{
private static readonly Lazy<SearchManager> _lazyInstance = new(() => new SearchManager());
public static SearchManager Instance => _lazyInstance.Value;
private readonly ConcurrentDictionary<string, ActiveSearch> _activeSearches = new();
private readonly ConcurrentDictionary<string, string> _lastErrors = new(StringComparer.OrdinalIgnoreCase);
public string GetSearchResultsDir() => MotelyPaths.SearchResultsDir;
private string? _motelyRoot;
private readonly SemaphoreSlim _lifecycleGate = new(1, 1);
private int _configuredThreadBudget = Environment.ProcessorCount;
private const int ReservedThreads = 1;
// ========== CIRCULAR QUEUE SCHEDULER ==========
// Fair round-robin scheduling for multiple concurrent searches
private readonly Queue<string> _roundRobinQueue = new();
private readonly Queue<string> _fastLaneQueue = new(); // Word list/DB searches (complete quickly)
private readonly object _queueLock = new();
private Task? _schedulerTask;
private CancellationTokenSource? _schedulerCts;
private bool _schedulerRunning = false;
/// <summary>Batches to run per search turn before rotating. BatchSize=3 means ~4.3M seeds per turn.</summary>
public int BatchesPerTurn { get; set; } = 100;
/// <summary>Default batch size for new searches (3 = ~43K seeds per batch)</summary>
public int DefaultBatchSize { get; set; } = 3;
private ISearchBroadcaster? _broadcaster;
internal void SetBroadcaster(ISearchBroadcaster broadcaster)
{
_broadcaster = broadcaster;
}
internal void SetMotelyRoot(string motelyRoot)
{
_motelyRoot = motelyRoot;
}
public bool TryGetLastError(string searchId, out string error)
{
error = "";
if (string.IsNullOrWhiteSpace(searchId))
return false;
if (!_lastErrors.TryGetValue(searchId, out var e))
return false;
error = e;
return !string.IsNullOrWhiteSpace(error);
}
public class ActiveSearch
{
public string SearchId { get; set; } = "";
public string FilterJaml { get; set; } = "";
public string Deck { get; set; } = "";
public string Stake { get; set; } = "";
public string? SeedSource { get; set; }
public List<string>? SeedList { get; set; }
public JsonSearchExecutor? Executor { get; set; }
public CancellationTokenSource? CancellationToken { get; set; }
public MotelySearchDatabase? Database { get; set; }
public Task? SearchTask { get; set; }
public int AssignedThreads { get; set; } = 1;
public int BatchSize { get; set; } = 3;
public long ResumeStartBatch { get; set; } = 0;
public int? CutoffOverride { get; set; }
public Guid RunInstanceId { get; set; } = Guid.Empty;
public string? StopReason { get; set; }
public List<string> ColumnNames { get; set; } = new();
public long CompletedBatches { get; set; } = 0;
public long TotalBatches { get; set; } = 0;
public long SeedsSearched { get; set; } = 0;
public double SeedsPerSecond { get; set; } = 0;
public int TotalResults { get; set; } = 0;
}
/// <summary>
/// Start a new search.
/// Returns immediate results from existing DB if available
/// </summary>
public async Task<(List<SearchResult> immediateResults, string searchId)> StartSearchAsync(
string filterJaml,
string deck,
string stake,
int seedCount,
long? startBatchOverride = null,
int? cutoffOverride = null,
string? seedSource = null,
List<string>? seedList = null)
{
await _lifecycleGate.WaitAsync();
try
{
Directory.CreateDirectory(MotelyPaths.SearchResultsDir);
if (!JamlConfigLoader.TryLoadFromJamlString(filterJaml, out var config, out var error) || config == null)
throw new ArgumentException(error ?? "Invalid filter");
var columnNames = config.GetColumnNames();
// Get filter name and sanitize it for searchId (spaces -> underscores, remove invalid chars)
var filterName = GetFilterName(filterJaml);
var sanitizedName = SanitizeFilterFileStem(filterName);
var searchId = $"{sanitizedName}_{deck}_{stake}";
var dbPath = Path.Combine(MotelyPaths.SearchResultsDir, $"{searchId}.db");
_lastErrors.TryRemove(searchId, out _);
// If this searchId already exists, stop it first (restart semantics)
if (_activeSearches.TryGetValue(searchId, out var existing))
{
var stopped = await StopSearchInternalAsync(existing, reason: "restart");
if (!stopped)
throw new InvalidOperationException($"Failed to stop existing search {searchId} (timeout)");
_activeSearches.TryRemove(searchId, out _);
}
// Immediate results from existing DB (if present)
var immediateResults = new List<SearchResult>();
if (File.Exists(dbPath))
{
immediateResults = GetTopResultsFromDb(dbPath, 1000);
}
var search = new ActiveSearch
{
SearchId = searchId,
FilterJaml = filterJaml,
Deck = deck,
Stake = stake,
SeedSource = seedSource,
SeedList = seedList,
CancellationToken = new CancellationTokenSource(),
ColumnNames = columnNames,
BatchSize = 3,
CutoffOverride = cutoffOverride
};
search.StopReason = null;
ReadResumeCursor(dbPath, columnNames, out var startBatch, out var batchSize);
if (startBatchOverride.HasValue)
search.ResumeStartBatch = Math.Max(0, startBatchOverride.Value);
else
search.ResumeStartBatch = startBatch;
if (batchSize > 0)
search.BatchSize = batchSize;
// (Re)open DB for active writes
search.Database = new MotelySearchDatabase(dbPath, columnNames);
// Save JAML metadata file so it can be retrieved even after search stops
var jamlPath = Path.Combine(MotelyPaths.SearchResultsDir, $"{searchId}.jaml");
File.WriteAllText(jamlPath, filterJaml);
// Automatically save filter to JamlFilters ecosystem
SaveFilterToEcosystem(filterJaml);
_activeSearches[searchId] = search;
await RebalanceAndRestartAllSearchesAsync();
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
_broadcaster?.Broadcast(JsonSerializer.Serialize(new { type = "filters_changed" }, options));
return (immediateResults, searchId);
}
finally
{
_lifecycleGate.Release();
}
}
/// <summary>
/// Get current top results and progress for a search
/// </summary>
public (List<SearchResult> results, int progressPercent) GetSearchStatus(string searchId)
{
var dbPath = Path.Combine(_searchResultsDir, $"{searchId}.db");
var results = new List<SearchResult>();
var progressPercent = 0;
if (_activeSearches.TryGetValue(searchId, out var search))
{
try
{
if (search.Database != null)
{
// GetTopResults() now returns List<SearchResult> directly - no dictionary conversion!
results = search.Database.GetTopResults(1000);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error getting search status from database for {searchId}: {ex.Message}");
results = new List<SearchResult>();
}
if (search.TotalBatches > 0)
{
progressPercent = (int)Math.Min(100, (search.CompletedBatches * 100) / search.TotalBatches);
}
}
if (results.Count == 0)
{
results = GetTopResultsFromDb(dbPath, 1000);
}
return (results, progressPercent);
}
public bool IsSearchRunning(string searchId)
{
return _activeSearches.ContainsKey(searchId);
}
public bool TryGetSearchProgress(string searchId, out long currentBatch, out long totalBatches)
{
currentBatch = 0;
totalBatches = 0;
if (!_activeSearches.TryGetValue(searchId, out var search))
return false;
currentBatch = search.CompletedBatches;
totalBatches = search.TotalBatches;
return true;
}
public bool TryGetSearchMetrics(
string searchId,
out long currentBatch,
out long totalBatches,
out long seedsSearched,
out double seedsPerSecond)
{
currentBatch = 0;
totalBatches = 0;
seedsSearched = 0;
seedsPerSecond = 0;
if (!_activeSearches.TryGetValue(searchId, out var search))
return false;
currentBatch = search.CompletedBatches;
totalBatches = search.TotalBatches;
seedsSearched = search.SeedsSearched;
seedsPerSecond = search.SeedsPerSecond;
return true;
}
public List<string> GetColumnNames(string searchId)
{
if (_activeSearches.TryGetValue(searchId, out var search) && search.ColumnNames.Count > 0)
return new List<string>(search.ColumnNames);
var dbPath = Path.Combine(_searchResultsDir, $"{searchId}.db");
return GetColumnNamesFromDb(dbPath);
}
public bool TryGetRunningSearch(out string searchId, out string filterJaml)
{
searchId = "";
filterJaml = "";
var first = _activeSearches.FirstOrDefault();
if (string.IsNullOrWhiteSpace(first.Key) || first.Value == null)
return false;
searchId = first.Key;
filterJaml = first.Value.FilterJaml;
return true;
}
public bool TryGetRunningSearchFilterJaml(string searchId, out string filterJaml)
{
filterJaml = "";
// First check active searches
if (_activeSearches.TryGetValue(searchId, out var search))
{
filterJaml = search.FilterJaml;
if (!string.IsNullOrWhiteSpace(filterJaml))
return true;
}
// If not in active searches, try to load from saved metadata file
var jamlPath = Path.Combine(_searchResultsDir, $"{searchId}.jaml");
if (File.Exists(jamlPath))
{
try
{
filterJaml = File.ReadAllText(jamlPath);
return !string.IsNullOrWhiteSpace(filterJaml);
}
catch (Exception ex)
{
// Log the error instead of silently swallowing it
Console.WriteLine($"Failed to read JAML metadata file {jamlPath}: {ex.Message}");
Console.WriteLine($"Stack trace: {ex.StackTrace}");
return false;
}
}
return false;
}
public bool TryGetSearchOverrides(string searchId, out long? startBatchOverride, out int? cutoffOverride)
{
startBatchOverride = null;
cutoffOverride = null;
if (!_activeSearches.TryGetValue(searchId, out var search))
return false;
cutoffOverride = search.CutoffOverride;
return true;
}
public List<string> GetRunningSearchIds()
{
return _activeSearches.Keys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase).ToList();
}
public void SetThreadBudget(int threadCount)
{
_configuredThreadBudget = Math.Max(1, threadCount);
}
// ========== CIRCULAR QUEUE SCHEDULER METHODS ==========
/// <summary>
/// Start the scheduler if not already running.
/// Called automatically when first search is enqueued.
/// </summary>
public void StartScheduler()
{
lock (_queueLock)
{
if (_schedulerRunning) return;
_schedulerRunning = true;
_schedulerCts = new CancellationTokenSource();
_schedulerTask = Task.Run(() => SchedulerLoopAsync(_schedulerCts.Token));
Console.WriteLine("[Scheduler] Started circular queue scheduler");
}
}
/// <summary>
/// Stop the scheduler gracefully.
/// </summary>
public async Task StopSchedulerAsync()
{
Task? taskToAwait;
lock (_queueLock)
{
if (!_schedulerRunning) return;
_schedulerCts?.Cancel();
taskToAwait = _schedulerTask;
}
if (taskToAwait != null)
{
try { await taskToAwait; } catch (OperationCanceledException) { }
}
lock (_queueLock)
{
_schedulerRunning = false;
_schedulerTask = null;
_schedulerCts?.Dispose();
_schedulerCts = null;
Console.WriteLine("[Scheduler] Stopped circular queue scheduler");
}
}
/// <summary>
/// Main scheduler loop - fair round-robin with fast lane priority.
/// </summary>
private async Task SchedulerLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
string? searchId = null;
bool isFastLane = false;
lock (_queueLock)
{
// Fast lane first (word list/DB searches complete quickly)
if (_fastLaneQueue.Count > 0)
{
searchId = _fastLaneQueue.Dequeue();
isFastLane = true;
}
// Then round-robin for sequential searches
else if (_roundRobinQueue.Count > 0)
{
searchId = _roundRobinQueue.Dequeue();
isFastLane = false;
}
}
if (searchId == null)
{
// No searches queued - wait a bit before checking again
try { await Task.Delay(100, ct); } catch (OperationCanceledException) { break; }
continue;
}
// Run the search turn
bool searchComplete = await RunSearchTurnAsync(searchId, isFastLane, ct);
// If not complete and not cancelled, re-enqueue for next turn
if (!searchComplete && !ct.IsCancellationRequested)
{
lock (_queueLock)
{
if (_activeSearches.ContainsKey(searchId))
{
if (isFastLane)
_fastLaneQueue.Enqueue(searchId);
else
_roundRobinQueue.Enqueue(searchId);
}
}
}
// Brief yield to allow other operations
await Task.Yield();
}
}
/// <summary>
/// Run one turn of a search (N batches for round-robin, or to completion for fast lane).
/// Returns true if search is complete.
/// </summary>
private async Task<bool> RunSearchTurnAsync(string searchId, bool runToCompletion, CancellationToken ct)
{
if (!_activeSearches.TryGetValue(searchId, out var search))
return true; // Search was removed, consider it complete
if (search.StopReason != null)
return true; // Search was stopped
try
{
// Broadcast that this search is now active
_broadcaster?.BroadcastToSearch(searchId, JsonSerializer.Serialize(new
{
type = "search_turn_started",
searchId = searchId,
isFastLane = runToCompletion
}));
var dbPath = Path.Combine(_searchResultsDir, $"{search.SearchId}.db");
ReadResumeCursor(dbPath, search.ColumnNames, out var startBatch, out var batchSize);
// For round-robin: limit to BatchesPerTurn batches
// For fast lane: run to completion (EndBatch = 0)
long endBatch = runToCompletion ? 0 : startBatch + BatchesPerTurn;
// Use all available threads for this turn (no splitting)
int threads = GetWorkerThreadBudget();
search.ResumeStartBatch = startBatch;
search.AssignedThreads = threads;
if (batchSize > 0) search.BatchSize = batchSize;
// Open/reopen database for this turn
search.Database?.Dispose();
search.Database = new MotelySearchDatabase(dbPath, search.ColumnNames);
var runId = Guid.NewGuid();
search.RunInstanceId = runId;
search.CancellationToken = new CancellationTokenSource();
// Link to scheduler cancellation
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct, search.CancellationToken.Token);
// Run the search for this turn
bool completed = await RunSearchTurnInternalAsync(runId, search, startBatch, endBatch, linkedCts.Token);
// Checkpoint database after turn
try { search.Database?.Checkpoint(); }
catch (Exception ex) { Console.WriteLine($"[SearchManager] Checkpoint failed for {search.SearchId}: {ex.Message}"); }
return completed;
}
catch (OperationCanceledException)
{
return false; // Will be re-enqueued if scheduler still running
}
catch (Exception ex)
{
Console.WriteLine($"[Scheduler] Error in search turn {searchId}: {ex.Message}");
_lastErrors[searchId] = ex.Message;
return true; // Consider it complete on error
}
}
/// <summary>
/// Internal method to run search for specified batch range.
/// </summary>
private async Task<bool> RunSearchTurnInternalAsync(Guid runId, ActiveSearch search, long startBatch, long endBatch, CancellationToken ct)
{
if (!JamlConfigLoader.TryLoadFromJamlString(search.FilterJaml, out var config, out var parseError) || config == null)
{
_lastErrors[search.SearchId] = parseError ?? "Invalid filter";
return true; // Complete on error
}
var searchParams = new JsonSearchParams
{
Threads = search.AssignedThreads,
BatchSize = search.BatchSize,
StartBatch = (ulong)Math.Max(0, startBatch),
EndBatch = (ulong)endBatch,
Cutoff = search.CutoffOverride ?? 0,
AutoCutoff = !search.CutoffOverride.HasValue || search.CutoffOverride.Value <= 0,
EnableDebug = false,
NoFancy = true,
Quiet = true
};
// Apply seed source or seed list
if (search.SeedList != null && search.SeedList.Count > 0)
searchParams.SeedList = search.SeedList;
else
ApplySeedSource(searchParams, search.SeedSource);
searchParams.ProgressCallback = (completedBatches, totalBatches, seedsSearched, seedsPerMs) =>
{
search.CompletedBatches = (long)searchParams.StartBatch + completedBatches;
search.TotalBatches = totalBatches > 0 ? (long)searchParams.StartBatch + totalBatches : 0;
search.SeedsSearched = seedsSearched;
search.SeedsPerSecond = seedsPerMs * 1000.0;
// Save batch position
try { search.Database?.SaveBatchPosition(search.CompletedBatches, searchParams.BatchSize); }
catch (Exception ex) { Console.WriteLine($"[SearchManager] SaveBatchPosition failed for {search.SearchId}: {ex.Message}"); }
// Broadcast progress
_broadcaster?.BroadcastToSearch(search.SearchId, JsonSerializer.Serialize(new
{
type = "progress",
searchId = search.SearchId,
currentBatch = search.CompletedBatches,
totalBatches = search.TotalBatches,
seedsSearched = search.SeedsSearched,
seedsPerSecond = search.SeedsPerSecond,
seedsFound = search.TotalResults
}));
};
var executor = new JsonSearchExecutor(config, searchParams, result =>
{
search.Database?.InsertRow(result.Seed, result.Score, result.TallyColumns);
search.TotalResults++;
_broadcaster?.BroadcastToSearch(search.SearchId, JsonSerializer.Serialize(new
{
type = "result",
searchId = search.SearchId,
result = new { seed = result.Seed, score = result.Score, tallies = result.TallyColumns },
columns = search.ColumnNames
}));
});
search.Executor = executor;
try
{
await Task.Run(() => executor.Execute(), ct);
}
catch (OperationCanceledException)
{
return false;
}
// Check if search naturally completed or just finished this turn's batches
bool naturallyComplete = search.TotalBatches > 0 && search.CompletedBatches >= search.TotalBatches;
if (naturallyComplete)
{
_broadcaster?.BroadcastToSearch(search.SearchId, JsonSerializer.Serialize(new
{
type = "search_completed",
searchId = search.SearchId,
seedsFound = search.TotalResults,
seedsSearched = search.SeedsSearched
}));
}
return naturallyComplete;
}
/// <summary>
/// Determines if a search should use the fast lane (small word list/DB searches).
/// </summary>
private bool IsFastLaneSearch(string? seedSource, List<string>? seedList)
{
// Seed list provided directly = fast lane
if (seedList != null && seedList.Count > 0 && seedList.Count < 100000)
return true;
// Word list or DB file source = fast lane
if (!string.IsNullOrWhiteSpace(seedSource))
{
if (seedSource.StartsWith("txt:", StringComparison.OrdinalIgnoreCase) ||
seedSource.StartsWith("csv:", StringComparison.OrdinalIgnoreCase) ||
seedSource.StartsWith("db:", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
/// <summary>
/// Enqueue a search for the scheduler. Automatically determines fast lane vs round-robin.
/// </summary>
public void EnqueueSearch(string searchId)
{
if (!_activeSearches.TryGetValue(searchId, out var search))
return;
bool fastLane = IsFastLaneSearch(search.SeedSource, search.SeedList);
lock (_queueLock)
{
if (fastLane)
_fastLaneQueue.Enqueue(searchId);
else
_roundRobinQueue.Enqueue(searchId);
}
Console.WriteLine($"[Scheduler] Enqueued search {searchId} ({(fastLane ? "fast lane" : "round-robin")})");
// Start scheduler if not running
StartScheduler();
}
/// <summary>
/// Get status of all active searches for UI display.
/// </summary>
public List<ActiveSearchStatus> GetActiveSearchesStatus()
{
var result = new List<ActiveSearchStatus>();
foreach (var kvp in _activeSearches)
{
var search = kvp.Value;
bool inQueue;
bool isFastLane;
lock (_queueLock)
{
isFastLane = _fastLaneQueue.Contains(search.SearchId);
inQueue = isFastLane || _roundRobinQueue.Contains(search.SearchId);
}
result.Add(new ActiveSearchStatus
{
SearchId = search.SearchId,
FilterName = GetFilterName(search.FilterJaml),
Deck = search.Deck,
Stake = search.Stake,
CompletedBatches = search.CompletedBatches,
TotalBatches = search.TotalBatches,
SeedsSearched = search.SeedsSearched,
SeedsPerSecond = search.SeedsPerSecond,
ResultsFound = search.TotalResults,
IsRunning = search.SearchTask != null && !search.SearchTask.IsCompleted,
IsFastLane = isFastLane,
InQueue = inQueue,
StopReason = search.StopReason
});
}
return result.OrderBy(s => s.SearchId).ToList();
}
public class ActiveSearchStatus
{
public string SearchId { get; set; } = "";
public string FilterName { get; set; } = "";
public string Deck { get; set; } = "";
public string Stake { get; set; } = "";
public long CompletedBatches { get; set; }
public long TotalBatches { get; set; }
public long SeedsSearched { get; set; }
public double SeedsPerSecond { get; set; }
public int ResultsFound { get; set; }
public bool IsRunning { get; set; }
public bool IsFastLane { get; set; }
public bool InQueue { get; set; }
public string? StopReason { get; set; }
}
private List<string> GetColumnNamesFromDb(string dbPath)
{
if (!File.Exists(dbPath)) return new List<string> { "seed", "score" };
try
{
using var conn = DuckDBConnectionFactory.CreateConnection(dbPath);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT column_name FROM information_schema.columns WHERE table_name='results' ORDER BY ordinal_position";
using var reader = cmd.ExecuteReader();
var cols = new List<string>();
while (reader.Read())
cols.Add(reader.GetString(0));
return cols.Count > 0 ? cols : new List<string> { "seed", "score" };
}
catch (Exception ex)
{
Console.WriteLine($"Error reading column names from database {dbPath}: {ex.Message}");
return new List<string> { "seed", "score" };
}
}
/// <summary>
/// Stop a search and return final results
/// </summary>
public async Task<List<SearchResult>> StopSearchAsync(string searchId)
{
await _lifecycleGate.WaitAsync();
try
{
if (_activeSearches.TryRemove(searchId, out var search))
{
var stopped = await StopSearchInternalAsync(search, reason: "user_stop");
if (!stopped)
{
// Put it back so we don't orphan a still-running search
_activeSearches[searchId] = search;
throw new InvalidOperationException($"Failed to stop search {searchId} (timeout)");
}
}
await RebalanceAndRestartAllSearchesAsync();
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
_broadcaster?.Broadcast(JsonSerializer.Serialize(new { type = "filters_changed" }, options));
var dbPath = Path.Combine(MotelyPaths.SearchResultsDir, $"{searchId}.db");
return GetTopResultsFromDb(dbPath, 1000);
}
finally
{
_lifecycleGate.Release();
}
}
public async Task StopAllSearchesAsync()
{
await _lifecycleGate.WaitAsync();
try
{
var ids = _activeSearches.Keys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase).ToList();
foreach (var id in ids)
{
if (_activeSearches.TryRemove(id, out var search))
{
// For stop_all, we don't re-add even if stop times out - force clear
await StopSearchInternalAsync(search, reason: "stop_all");
}
}
_broadcaster?.Broadcast(JsonSerializer.Serialize(new { type = "filters_changed" }));
}
finally
{
_lifecycleGate.Release();
}
}
public async Task ClearAllSearchesAsync()
{
await _lifecycleGate.WaitAsync();
try
{
// Clear all active searches
var ids = _activeSearches.Keys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase).ToList();
foreach (var id in ids)
{
if (_activeSearches.TryRemove(id, out var search))
{
await StopSearchInternalAsync(search, reason: "clear_all");
}
}
// Clear all stored results by deleting all database files
if (Directory.Exists(MotelyPaths.SearchResultsDir))
{
var dbFiles = Directory.GetFiles(MotelyPaths.SearchResultsDir, "*.db");
foreach (var file in dbFiles)
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting old search file {file}: {ex.Message}");
// Ignore file deletion errors
}
}
}
// Broadcast clear event
_broadcaster?.Broadcast(JsonSerializer.Serialize(new { type = "results_cleared" }));
}
finally
{
_lifecycleGate.Release();
}
}
private async Task<bool> StopSearchInternalAsync(ActiveSearch search, string reason)
{
_broadcaster?.BroadcastToSearch(search.SearchId, JsonSerializer.Serialize(new { type = "search_halted", searchId = search.SearchId, reason }));
search.StopReason = reason;
try
{
search.Executor?.Cancel();
}
catch (Exception ex)
{
Console.WriteLine($"Error canceling executor for search {search.SearchId}: {ex.Message}");
}
try
{
search.CancellationToken?.Cancel();
}
catch (Exception ex)
{
Console.WriteLine($"Error canceling cancellation token for search {search.SearchId}: {ex.Message}");
}
try
{
search.CancellationToken?.Dispose();
search.CancellationToken = null;
}
catch { }
var timeout = TimeSpan.FromSeconds(1);
var completed = true;
if (search.SearchTask != null)
{
try
{
var finished = await Task.WhenAny(search.SearchTask, Task.Delay(timeout));
completed = ReferenceEquals(finished, search.SearchTask);
}
catch (Exception ex)
{
Console.WriteLine($"Error waiting for search task to complete for {search.SearchId}: {ex.Message}");
completed = false;
}
}
if (!completed)
return false;
if (reason is "user_stop" or "stop_all")
{
try
{
var dbPath = search.Database?.DatabasePath
?? Path.Combine(MotelyPaths.SearchResultsDir, $"{search.SearchId}.db");
await ExportTopResultsToFertilizerAsync(dbPath, limit: 1000);
}
catch (Exception ex)
{
Console.WriteLine($"Error exporting results to fertilizer for {search.SearchId}: {ex.Message}");
}
}
search.Executor = null;
search.SearchTask = null;
try
{
search.Database?.Checkpoint();
}
catch (Exception ex)
{
Console.WriteLine($"Error checkpointing database for search {search.SearchId}: {ex.Message}");
}
try
{
search.Database?.Dispose();
}
catch (Exception ex)
{
Console.WriteLine($"Error disposing database for search {search.SearchId}: {ex.Message}");
}
return true;
}
private int GetWorkerThreadBudget()
{
return Math.Max(1, _configuredThreadBudget - ReservedThreads);
}
private Dictionary<string, int> ComputeThreadAllocations(IReadOnlyList<string> searchIds)
{
var allocations = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
if (searchIds.Count == 0)
return allocations;
var budget = GetWorkerThreadBudget();
var baseThreads = Math.Max(1, budget / searchIds.Count);
var remainder = Math.Max(0, budget - (baseThreads * searchIds.Count));
for (var i = 0; i < searchIds.Count; i++)
{
allocations[searchIds[i]] = baseThreads + (i < remainder ? 1 : 0);
}
return allocations;
}
private void ReadResumeCursor(string dbPath, List<string> columnNames, out long startBatch, out int batchSize)
{
startBatch = 0;
batchSize = 0;
try
{
using var db = new MotelySearchDatabase(dbPath, columnNames);
var (lastBatch, lastBatchSize) = db.GetLastBatchPosition();
if (lastBatch.HasValue)
startBatch = lastBatch.Value;
if (lastBatchSize.HasValue)
batchSize = lastBatchSize.Value;
}
catch (Exception ex)
{
Console.WriteLine($"Error reading resume cursor from {dbPath}: {ex.Message}");
startBatch = 0;
batchSize = 0;
}
}
private void ApplySeedSource(JsonSearchParams searchParams, string? seedSource)
{
if (string.IsNullOrWhiteSpace(seedSource))
return;
var s = seedSource.Trim();
if (string.Equals(s, "all", StringComparison.OrdinalIgnoreCase))
return;
if (string.Equals(s, "new", StringComparison.OrdinalIgnoreCase))
return;
if (s.StartsWith("random:", StringComparison.OrdinalIgnoreCase))
{
var raw = s.Substring("random:".Length);
if (int.TryParse(raw, out var n) && n > 0)
{
searchParams.RandomSeeds = n;
}
return;