Skip to content

Commit 4e0cfe1

Browse files
authored
Merge pull request #35 from cogpy/claude/loving-archimedes-r7fcwy
Fix seven bugs found during the refactor; give tests their own temp paths
2 parents c8d2171 + f1e48f6 commit 4e0cfe1

18 files changed

Lines changed: 470 additions & 124 deletions

‎include/bolt/ai/koboldcpp_provider.hpp‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,20 @@ class KoboldCppProvider : public AICompletionProvider {
157157
bool detect_api_mode();
158158
};
159159

160+
namespace detail {
161+
162+
// Request bodies exactly as KoboldCppProvider posts them. Every string taken from the caller or the
163+
// configuration is JSON-escaped. Declared here so that the tests can check them without a server.
164+
165+
/// Body for POST /v1/completions.
166+
std::string buildOpenAICompletionRequest(const std::string& prompt, int max_tokens, const KoboldCppConfig& config);
167+
168+
/// Body for POST /v1/chat/completions; each message is a (role, content) pair.
169+
std::string buildOpenAIChatRequest(const std::vector<std::pair<std::string, std::string>>& messages,
170+
const KoboldCppConfig& config);
171+
172+
} // namespace detail
173+
160174
} // namespace ai
161175
} // namespace bolt
162176

‎include/bolt/collaboration/collaboration_protocol.hpp‎

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
#include <algorithm>
55
#include <cctype>
6+
#include <exception>
67
#include <functional>
78
#include <map>
89
#include <memory>
@@ -50,14 +51,39 @@ inline std::string escapeJsonString(const std::string& str) {
5051
return result;
5152
}
5253

53-
// Reads the integer value of "key" from a flat JSON object; returns 0 when the key is absent.
54+
// Reads the escaped body of a JSON string value starting at `pos` (just after the opening quote) up to
55+
// the closing unescaped quote, undoing escapeJsonString. An unknown escape yields the escaped character.
56+
inline std::string unescapeJsonStringAt(const std::string& data, size_t pos) {
57+
std::string result;
58+
for (; pos < data.size() && data[pos] != '"'; ++pos) {
59+
char c = data[pos];
60+
if (c == '\\' && pos + 1 < data.size()) {
61+
c = data[++pos];
62+
if (c == 'n')
63+
c = '\n';
64+
else if (c == 'r')
65+
c = '\r';
66+
else if (c == 't')
67+
c = '\t';
68+
}
69+
result += c;
70+
}
71+
return result;
72+
}
73+
74+
// Reads the integer value of "key" from a flat JSON object; returns 0 when the key is absent or its
75+
// value is not a number that fits in an int.
5476
inline int extractJsonInt(const std::string& data, const std::string& key) {
5577
auto pos = data.find("\"" + key + "\":");
5678
if (pos == std::string::npos)
5779
return 0;
5880
pos = data.find(":", pos) + 1;
5981
auto end = data.find_first_of(",}", pos);
60-
return std::stoi(data.substr(pos, end - pos));
82+
try {
83+
return std::stoi(data.substr(pos, end - pos));
84+
} catch (const std::exception&) {
85+
return 0;
86+
}
6187
}
6288

6389
} // namespace detail
@@ -71,8 +97,8 @@ struct ProtocolMessage {
7197
std::string serialize() const {
7298
std::string result = "{";
7399
result += "\"type\":" + std::to_string(static_cast<int>(type)) + ",";
74-
result += "\"documentId\":\"" + documentId + "\",";
75-
result += "\"userId\":\"" + userId + "\",";
100+
result += "\"documentId\":\"" + detail::escapeJsonString(documentId) + "\",";
101+
result += "\"userId\":\"" + detail::escapeJsonString(userId) + "\",";
76102
result += "\"data\":\"" + detail::escapeJsonString(data) + "\"";
77103
result += "}";
78104
return result;
@@ -93,8 +119,7 @@ struct ProtocolMessage {
93119
if (pos == std::string::npos)
94120
return "";
95121
pos = data.find("\":\"", pos) + 3;
96-
auto end = data.find("\"", pos);
97-
return data.substr(pos, end - pos);
122+
return detail::unescapeJsonStringAt(data, pos);
98123
}
99124
};
100125

‎include/bolt/core/editor_store.hpp‎

Lines changed: 68 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -69,71 +69,79 @@ class EditorStore {
6969
ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty");
7070
doc.validateDocument();
7171

72-
std::lock_guard<std::mutex> lock(mutex_);
72+
{
73+
std::lock_guard<std::mutex> lock(mutex_);
7374

74-
if (documents_.size() >= MAX_OPEN_DOCUMENTS && documents_.find(path) == documents_.end()) {
75-
throw EditorException(ErrorCode::EDITOR_OPERATION_FAILED,
76-
"Too many open documents: " + std::to_string(documents_.size()) +
77-
" >= " + std::to_string(MAX_OPEN_DOCUMENTS));
78-
}
75+
if (documents_.size() >= MAX_OPEN_DOCUMENTS && documents_.find(path) == documents_.end()) {
76+
throw EditorException(ErrorCode::EDITOR_OPERATION_FAILED,
77+
"Too many open documents: " + std::to_string(documents_.size()) +
78+
" >= " + std::to_string(MAX_OPEN_DOCUMENTS));
79+
}
7980

80-
documents_[path] = doc;
81+
documents_[path] = doc;
82+
}
8183
notifyListeners();
8284
}
8385

8486
void updateScrollPosition(const std::string& path, int line, int character) {
8587
ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty");
8688

87-
std::lock_guard<std::mutex> lock(mutex_);
89+
{
90+
std::lock_guard<std::mutex> lock(mutex_);
8891

89-
auto it = findDocumentOrThrowLocked(path, "Document not found: ");
92+
auto it = findDocumentOrThrowLocked(path, "Document not found: ");
9093

91-
EditorDocument::ScrollPosition pos{line, character};
92-
pos.validate();
94+
EditorDocument::ScrollPosition pos{line, character};
95+
pos.validate();
9396

94-
it->second.scroll = pos;
97+
it->second.scroll = pos;
98+
}
9599
notifyListeners();
96100
}
97101

98102
void updateFoldingRanges(const std::string& path, const std::vector<FoldRange>& ranges) {
99103
ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty");
100104

101-
std::lock_guard<std::mutex> lock(mutex_);
105+
{
106+
std::lock_guard<std::mutex> lock(mutex_);
102107

103-
auto it = findDocumentOrThrowLocked(path, "Document not found: ");
108+
auto it = findDocumentOrThrowLocked(path, "Document not found: ");
104109

105-
if (ranges.size() > MAX_FOLDING_RANGES) {
106-
throw EditorException(ErrorCode::EDITOR_FOLDING_ERROR,
107-
"Too many folding ranges: " + std::to_string(ranges.size()) + " > " +
108-
std::to_string(MAX_FOLDING_RANGES));
109-
}
110+
if (ranges.size() > MAX_FOLDING_RANGES) {
111+
throw EditorException(ErrorCode::EDITOR_FOLDING_ERROR,
112+
"Too many folding ranges: " + std::to_string(ranges.size()) + " > " +
113+
std::to_string(MAX_FOLDING_RANGES));
114+
}
110115

111-
it->second.foldingRanges = ranges;
116+
it->second.foldingRanges = ranges;
117+
}
112118
notifyListeners();
113119
}
114120

115121
void toggleFold(const std::string& path, size_t line) {
116122
ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty");
117123

118-
std::lock_guard<std::mutex> lock(mutex_);
124+
{
125+
std::lock_guard<std::mutex> lock(mutex_);
119126

120-
auto it = findDocumentOrThrowLocked(path, "Document not found: ");
127+
auto it = findDocumentOrThrowLocked(path, "Document not found: ");
121128

122-
auto& ranges = it->second.foldingRanges;
123-
bool found = false;
124-
for (auto& range : ranges) {
125-
if (line >= range.startLine && line <= range.endLine) {
126-
range.isFolded = !range.isFolded;
127-
found = true;
128-
notifyListeners();
129-
break;
129+
auto& ranges = it->second.foldingRanges;
130+
bool found = false;
131+
for (auto& range : ranges) {
132+
if (line >= range.startLine && line <= range.endLine) {
133+
range.isFolded = !range.isFolded;
134+
found = true;
135+
break;
136+
}
130137
}
131-
}
132138

133-
if (!found) {
134-
throw EditorException(ErrorCode::EDITOR_FOLDING_ERROR,
135-
"No foldable range found at line " + std::to_string(line) + " in " + path);
139+
if (!found) {
140+
throw EditorException(ErrorCode::EDITOR_FOLDING_ERROR,
141+
"No foldable range found at line " + std::to_string(line) + " in " + path);
142+
}
136143
}
144+
notifyListeners();
137145
}
138146

139147
std::vector<FoldRange> getFoldingRanges(const std::string& path) const {
@@ -148,6 +156,10 @@ class EditorStore {
148156
return {};
149157
}
150158

159+
// The returned pointer refers to an entry of the documents map and is not
160+
// protected by the lock once this returns: it is only valid until that
161+
// document is closed, and reading or writing through it is not
162+
// synchronised with other threads using the store.
151163
EditorDocument* getCurrentDocument() {
152164
std::lock_guard<std::mutex> lock(mutex_);
153165

@@ -163,12 +175,14 @@ class EditorStore {
163175
"File path too long: " + std::to_string(path.length()));
164176
}
165177

166-
std::lock_guard<std::mutex> lock(mutex_);
167-
selectedFile_ = path;
178+
{
179+
std::lock_guard<std::mutex> lock(mutex_);
180+
selectedFile_ = path;
181+
}
168182
notifyListeners();
169183
}
170184

171-
const std::string& getSelectedFile() const {
185+
std::string getSelectedFile() const {
172186
std::lock_guard<std::mutex> lock(mutex_);
173187
return selectedFile_;
174188
}
@@ -201,15 +215,17 @@ class EditorStore {
201215
void closeDocument(const std::string& path) {
202216
ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty");
203217

204-
std::lock_guard<std::mutex> lock(mutex_);
218+
{
219+
std::lock_guard<std::mutex> lock(mutex_);
205220

206-
auto it = findDocumentOrThrowLocked(path, "Cannot close document that is not open: ");
221+
auto it = findDocumentOrThrowLocked(path, "Cannot close document that is not open: ");
207222

208-
documents_.erase(it);
223+
documents_.erase(it);
209224

210-
// Clear selection if this was the selected file
211-
if (selectedFile_ == path) {
212-
selectedFile_.clear();
225+
// Clear selection if this was the selected file
226+
if (selectedFile_ == path) {
227+
selectedFile_.clear();
228+
}
213229
}
214230

215231
notifyListeners();
@@ -229,9 +245,16 @@ class EditorStore {
229245
return it;
230246
}
231247

248+
// Must be called WITHOUT mutex_ held. The listeners are copied under the
249+
// lock and invoked after it is released, so a listener may call back into
250+
// the store (mutex_ is not recursive).
232251
void notifyListeners() {
233-
// Note: mutex should already be locked when this is called
234-
for (auto& listener : listeners_) {
252+
std::vector<std::function<void()>> listeners;
253+
{
254+
std::lock_guard<std::mutex> lock(mutex_);
255+
listeners = listeners_;
256+
}
257+
for (auto& listener : listeners) {
235258
try {
236259
if (listener) {
237260
listener();

‎include/bolt/test_framework.hpp‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,41 @@
22
#define BOLT_TEST_FRAMEWORK_HPP_
33

44
#include <chrono>
5+
#include <cstdint>
56
#include <exception>
7+
#include <filesystem>
68
#include <functional>
79
#include <iostream>
10+
#include <random>
811
#include <sstream>
912
#include <string>
1013
#include <vector>
1114

1215
namespace bolt {
1316
namespace test {
1417

18+
// Returns a path in the system temporary directory for a file or directory
19+
// that a test creates. The same test sources are built into several test
20+
// programs and CTest runs those in parallel, so a fixed path would be shared
21+
// between processes. The result is `name` with a tag inserted before its
22+
// extension; the tag is chosen once per process, so the same name always
23+
// gives the same path within one run and a different one in another process.
24+
inline std::string uniqueTempPath(const std::string& name) {
25+
static const std::string process_tag = [] {
26+
static const char anchor = 0;
27+
const auto ticks = static_cast<std::uint64_t>(std::chrono::steady_clock::now().time_since_epoch().count());
28+
const auto address = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(&anchor));
29+
std::random_device entropy;
30+
std::ostringstream tag;
31+
tag << std::hex << (ticks ^ (address << 20)) << entropy();
32+
return tag.str();
33+
}();
34+
35+
const std::filesystem::path file(name);
36+
const std::string unique_name = file.stem().string() + "_" + process_tag + file.extension().string();
37+
return (std::filesystem::temp_directory_path() / unique_name).string();
38+
}
39+
1540
class TestFailure : public std::exception {
1641
public:
1742
TestFailure(const std::string& message, const std::string& file, int line)
@@ -172,6 +197,14 @@ class TestSuite {
172197
std::cout << "ERROR" << std::endl;
173198
std::cout << " " << result.error_message << std::endl;
174199
}
200+
} catch (...) {
201+
result.passed = false;
202+
result.error_message = "Unexpected exception: Unknown exception";
203+
failed++;
204+
if (verbose) {
205+
std::cout << "ERROR" << std::endl;
206+
std::cout << " " << result.error_message << std::endl;
207+
}
175208
}
176209

177210
auto end = std::chrono::high_resolution_clock::now();

‎include/bolt/utils/tensor_utils.hpp‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,8 @@ class TensorUtils {
8989
static float calculateQuantizationError(ggml_tensor* original, ggml_tensor* quantized) {
9090
std::vector<float> orig_data, quant_data;
9191
int64_t n_orig = extractComparableData(original, quantized, orig_data, quant_data);
92+
if (n_orig == 0)
93+
return 0.0f; // No elements: no error, rather than 0/0.
9294

9395
double mse = 0.0;
9496
for (int64_t i = 0; i < n_orig; i++) {
@@ -105,6 +107,8 @@ class TensorUtils {
105107
static float calculateMAE(ggml_tensor* original, ggml_tensor* quantized) {
106108
std::vector<float> orig_data, quant_data;
107109
int64_t n = extractComparableData(original, quantized, orig_data, quant_data);
110+
if (n == 0)
111+
return 0.0f;
108112

109113
double mae = 0.0;
110114
for (int64_t i = 0; i < n; i++)
@@ -141,6 +145,8 @@ class TensorUtils {
141145
return stats;
142146
int64_t n = ggml_nelements(tensor);
143147
stats.n_elements = n;
148+
if (n == 0)
149+
return stats; // All statistics stay zero for an empty tensor.
144150
std::vector<float> data(n);
145151
extractFloatData(tensor, data);
146152
stats.min = std::numeric_limits<float>::max();

0 commit comments

Comments
 (0)