forked from microsoft/kernel-memory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchConfig.cs
More file actions
234 lines (202 loc) · 8.99 KB
/
SearchConfig.cs
File metadata and controls
234 lines (202 loc) · 8.99 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
// Copyright (c) Microsoft. All rights reserved.
using System.Text.Json.Serialization;
using KernelMemory.Core.Config.Validation;
namespace KernelMemory.Core.Config;
/// <summary>
/// Global search configuration settings.
/// Applied as defaults across all search operations unless overridden.
/// </summary>
public sealed class SearchConfig : IValidatable
{
/// <summary>
/// Default minimum relevance score threshold (0.0-1.0).
/// Results below this score are filtered out.
/// Default: 0.3 (moderate threshold).
/// </summary>
[JsonPropertyName("defaultMinRelevance")]
public float DefaultMinRelevance { get; set; } = Constants.SearchDefaults.DefaultMinRelevance;
/// <summary>
/// Default maximum number of results to return per search.
/// Default: 20 results.
/// </summary>
[JsonPropertyName("defaultLimit")]
public int DefaultLimit { get; set; } = Constants.SearchDefaults.DefaultLimit;
/// <summary>
/// Search timeout in seconds per node.
/// If a node takes longer than this, it times out and is excluded from results.
/// Default: 30 seconds.
/// </summary>
[JsonPropertyName("searchTimeoutSeconds")]
public int SearchTimeoutSeconds { get; set; } = Constants.SearchDefaults.DefaultSearchTimeoutSeconds;
/// <summary>
/// Default maximum results to retrieve from each node (memory safety).
/// Prevents memory exhaustion from large result sets.
/// Results are sorted by (relevance DESC, createdAt DESC) before limiting.
/// Default: 1000 results per node.
/// </summary>
[JsonPropertyName("maxResultsPerNode")]
public int MaxResultsPerNode { get; set; } = Constants.SearchDefaults.DefaultMaxResultsPerNode;
/// <summary>
/// Default nodes to search when no explicit --nodes flag is provided.
/// Use ["*"] to search all configured nodes (default).
/// Use specific node IDs like ["personal", "work"] to limit search scope.
/// </summary>
[JsonPropertyName("defaultNodes")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1819:Properties should not return arrays")]
public string[] DefaultNodes { get; set; } = [Constants.SearchDefaults.AllNodesWildcard];
/// <summary>
/// Nodes to exclude from search by default.
/// These nodes are never searched unless explicitly requested via --nodes flag.
/// Default: empty (no exclusions).
/// </summary>
[JsonPropertyName("excludeNodes")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1819:Properties should not return arrays")]
public string[] ExcludeNodes { get; set; } = [];
/// <summary>
/// Maximum nesting depth for query parentheses.
/// Prevents DoS attacks via deeply nested queries.
/// Default: 10 levels.
/// </summary>
[JsonPropertyName("maxQueryDepth")]
public int MaxQueryDepth { get; set; } = Constants.SearchDefaults.MaxQueryDepth;
/// <summary>
/// Maximum number of boolean operators (AND/OR/NOT) in a single query.
/// Prevents query complexity attacks.
/// Default: 50 operators.
/// </summary>
[JsonPropertyName("maxBooleanOperators")]
public int MaxBooleanOperators { get; set; } = Constants.SearchDefaults.MaxBooleanOperators;
/// <summary>
/// Maximum length of a field value in query (characters).
/// Prevents oversized query values.
/// Default: 1000 characters.
/// </summary>
[JsonPropertyName("maxFieldValueLength")]
public int MaxFieldValueLength { get; set; } = Constants.SearchDefaults.MaxFieldValueLength;
/// <summary>
/// Maximum time allowed for query parsing (milliseconds).
/// Prevents regex catastrophic backtracking.
/// Default: 1000ms (1 second).
/// </summary>
[JsonPropertyName("queryParseTimeoutMs")]
public int QueryParseTimeoutMs { get; set; } = Constants.SearchDefaults.QueryParseTimeoutMs;
/// <summary>
/// Default snippet length in characters when --snippet flag is used.
/// Default: 200 characters.
/// </summary>
[JsonPropertyName("snippetLength")]
public int SnippetLength { get; set; } = Constants.SearchDefaults.DefaultSnippetLength;
/// <summary>
/// Default maximum number of snippets per result when --snippet flag is used.
/// Default: 1 snippet.
/// </summary>
[JsonPropertyName("maxSnippetsPerResult")]
public int MaxSnippetsPerResult { get; set; } = Constants.SearchDefaults.DefaultMaxSnippetsPerResult;
/// <summary>
/// Separator string between multiple snippets.
/// Default: "..." (ellipsis).
/// </summary>
[JsonPropertyName("snippetSeparator")]
public string SnippetSeparator { get; set; } = Constants.SearchDefaults.DefaultSnippetSeparator;
/// <summary>
/// Prefix marker for highlighting matched terms.
/// Default: "<mark>" (HTML-style).
/// </summary>
[JsonPropertyName("highlightPrefix")]
public string HighlightPrefix { get; set; } = Constants.SearchDefaults.DefaultHighlightPrefix;
/// <summary>
/// Suffix marker for highlighting matched terms.
/// Default: "</mark>" (HTML-style).
/// </summary>
[JsonPropertyName("highlightSuffix")]
public string HighlightSuffix { get; set; } = Constants.SearchDefaults.DefaultHighlightSuffix;
/// <summary>
/// Validates the search configuration.
/// </summary>
/// <param name="path">Configuration path for error reporting.</param>
public void Validate(string path)
{
// Validate min relevance score
if (this.DefaultMinRelevance < Constants.SearchDefaults.MinRelevanceScore || this.DefaultMinRelevance > Constants.SearchDefaults.MaxRelevanceScore)
{
throw new ConfigException($"{path}.DefaultMinRelevance",
$"Must be between {Constants.SearchDefaults.MinRelevanceScore} and {Constants.SearchDefaults.MaxRelevanceScore}");
}
// Validate default limit
if (this.DefaultLimit <= 0)
{
throw new ConfigException($"{path}.DefaultLimit", "Must be greater than 0");
}
// Validate timeout
if (this.SearchTimeoutSeconds <= 0)
{
throw new ConfigException($"{path}.SearchTimeoutSeconds", "Must be greater than 0");
}
// Validate max results per node
if (this.MaxResultsPerNode <= 0)
{
throw new ConfigException($"{path}.MaxResultsPerNode", "Must be greater than 0");
}
// Validate default nodes
if (this.DefaultNodes.Length == 0)
{
throw new ConfigException($"{path}.DefaultNodes",
"Must specify at least one node or use '*' for all nodes");
}
// Validate no contradictory node configuration
if (this.DefaultNodes.Length == 1 && this.DefaultNodes[0] == Constants.SearchDefaults.AllNodesWildcard)
{
// Using wildcard - excludeNodes is OK
}
else
{
// Using specific nodes - check for contradictions
var defaultNodesSet = new HashSet<string>(this.DefaultNodes, StringComparer.OrdinalIgnoreCase);
var excludeNodesSet = new HashSet<string>(this.ExcludeNodes, StringComparer.OrdinalIgnoreCase);
var conflicts = defaultNodesSet.Intersect(excludeNodesSet).ToArray();
if (conflicts.Length > 0)
{
throw new ConfigException($"{path}.DefaultNodes",
$"Contradictory configuration: nodes [{string.Join(", ", conflicts)}] appear in both DefaultNodes and ExcludeNodes");
}
}
// Validate query complexity limits
if (this.MaxQueryDepth <= 0)
{
throw new ConfigException($"{path}.MaxQueryDepth", "Must be greater than 0");
}
if (this.MaxBooleanOperators <= 0)
{
throw new ConfigException($"{path}.MaxBooleanOperators", "Must be greater than 0");
}
if (this.MaxFieldValueLength <= 0)
{
throw new ConfigException($"{path}.MaxFieldValueLength", "Must be greater than 0");
}
if (this.QueryParseTimeoutMs <= 0)
{
throw new ConfigException($"{path}.QueryParseTimeoutMs", "Must be greater than 0");
}
// Validate snippet settings
if (this.SnippetLength <= 0)
{
throw new ConfigException($"{path}.SnippetLength", "Must be greater than 0");
}
if (this.MaxSnippetsPerResult <= 0)
{
throw new ConfigException($"{path}.MaxSnippetsPerResult", "Must be greater than 0");
}
if (string.IsNullOrEmpty(this.SnippetSeparator))
{
throw new ConfigException($"{path}.SnippetSeparator", "Cannot be null or empty");
}
if (string.IsNullOrEmpty(this.HighlightPrefix))
{
throw new ConfigException($"{path}.HighlightPrefix", "Cannot be null or empty");
}
if (string.IsNullOrEmpty(this.HighlightSuffix))
{
throw new ConfigException($"{path}.HighlightSuffix", "Cannot be null or empty");
}
}
}