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
|
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
const crypto = require('crypto');
const { globalCache } = require('./cache.js');
const { aiSnipTestFailure, aiAnalyzeLogChunk } = require('./aiTools.js');
const { logger } = require('./logger.js');
function chunkLogFile(data, chunkSize = 1500) {
let lines = data.split('\n').slice(0, -4);
// eslint-disable-next-line no-unused-vars
lines = lines.map((line, index) => line.replace(/^agent:\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2} \S+:\d+:\s/, '').trim());
lines = lines.map((line, index) => `${index + 1}: ${line}`);
let chunks = [];
for (let i = lines.length; i > 0; i -= chunkSize) {
const startIndex = Math.max(0, i - chunkSize);
chunks.unshift(lines.slice(startIndex, i).join('\n'));
}
return chunks;
}
async function snipTestFailureFromLog(logtext, platformIdentifier) {
logger.info("snipping log...")
// create a sha hash of the logtext to use as a cache key
const hash = crypto.createHash('sha256');
hash.update(logtext);
const cacheKey = hash.digest('hex');
if (globalCache[cacheKey]) {
logger.info("Snip Cache hit!")
return globalCache[cacheKey];
}
logger.info("Snip cache miss! Processing log...")
let pattern = new RegExp('[0-9]{1,} failed', 'g');
let match;
let result = {}
let totalCount = 0;
while ((match = pattern.exec(logtext)) !== null) {
let precedingChar = logtext.charAt(match.index - 1);
if (precedingChar === '0') {
continue;
}
let filename = "";
let tstnameindex = 0;
tstnameindex = logtext.lastIndexOf("********* Start testing of ", match.index) + 27;
let tstname = logtext.substring(tstnameindex, logtext.indexOf("*********", tstnameindex) - 1);
// Extract the filename of the test being compiled
let compileStartIndex = -1
// let compileStartIndex = logtext.lastIndexOf("Entering directory", tstnameindex);
if (compileStartIndex === -1) {
compileStartIndex = logtext.lastIndexOf("Working Directory", tstnameindex);
let compileLine = logtext.substring(compileStartIndex, logtext.indexOf('\n', compileStartIndex));
let filenameMatch = compileLine.match(/.+[/](tests.+?)'?[,\s]?$/);
if (filenameMatch && !filenameMatch[1].includes('/../')) {
filename = filenameMatch
? filenameMatch[1] + `/${filenameMatch[1].includes('tst_') ? '' : 'tst_'}${filenameMatch[1].split('/').pop()}.cpp`
: "Unknown file";
}
}
if (compileStartIndex === -1 || !filename) {
compileStartIndex = logtext.lastIndexOf("Running test command line", tstnameindex);
let compileLine = logtext.substring(compileStartIndex, logtext.indexOf('\n', compileStartIndex));
let filenameMatch = compileLine.match(/\/(tests\/.*?)(?=',)/);
filename = filenameMatch
? filenameMatch[1] + '.cpp'
: "Unknown file";
}
// logger.info(filename)
if (parseInt(match[0].match('[0-9]{0,}')[0]) > 50) {
result[tstname] = {
source_file: filename, log_snip: "Too many fail cases. Not printing the failures here."
+ " See the original log for failure details."
};
break;
}
let logsnip = logtext.substring(tstnameindex, logtext.indexOf("********* Finished testing of ", tstnameindex));
let failcasematch;
let failcasepattern = new RegExp('FAIL! {2}: ', 'g');
while ((failcasematch = failcasepattern.exec(logsnip)) !== null) {
// Windows logs have the failure location marked with "failure location"
// Linux logs have the failure location marked with "Loc: "
let failloc = logsnip.indexOf("Loc: ", failcasematch.index);
if (failloc === -1) {
failloc = logsnip.indexOf(": failure location", failcasematch.index)
}
let failcasestring = logsnip.substring(failcasematch.index, logsnip.indexOf('\n', failloc));
// Strip the line number from the fail case string, line by line
let lines = failcasestring.split('\n');
lines.forEach((line, index) => {
lines[index] = line.replace(/.*\w+\.go:\d+: /, '')
});
failcasestring = lines.join('\n');
let testFunctionName = ""
try {
testFunctionName = logsnip.substring(failcasematch.index, logsnip.indexOf("\n", failcasematch.index)).match(/::(.+?)\(.*\)/)[1];
} catch (error) {
logger.info(error);
}
result[tstname] = {
source_file: filename.trim(),
testCaseName: tstname,
testFunctionName: testFunctionName,
fullSnip: logsnip,
log_snip: failcasestring.trim()
};
}
totalCount += 1;
}
if (totalCount === 0) {
logger.info("No test failures found.")
return { errors: [], log: '' };
}
return aiSnipTestFailure(result, platformIdentifier, cacheKey);
}
async function processChunks(chunks, platformIdentifier) {
let errors = [];
return new Promise((resolve, reject) => {
let count = chunks.length;
function checkDone() {
count--;
if (count === 0) {
errors.sort((a, b) => a.significant_line_number - b.significant_line_number);
logger.info(`Finished processing chunks.`);
resolve(errors);
}
}
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
logger.info(`Processing chunk ${i + 1} of ${chunks.length}`);
// Trim each line of the chunk to 500 characters
const trimmedChunk = chunk.split('\n').map(line => line.length > 256 ? line.slice(0, 256) + '...' : line).join('\n');
aiAnalyzeLogChunk(trimmedChunk, platformIdentifier).then((analysisResult) => {
if (analysisResult.is_critical_error && !analysisResult.is_intentional_error) {
analysisResult.platformIdentifier = platformIdentifier;
errors.push(analysisResult);
}
checkDone();
}).catch((error) => {
logger.info(`Error processing chunk: ${error}`);
reject(error);
});
}
});
}
async function getAnalysis(logText = "", platformIdentifier = "") {
return new Promise((resolve, reject) => {
// Check the cache
const hash = crypto.createHash('sha256');
hash.update(logText);
const cacheKey = hash.digest('hex');
if (globalCache[cacheKey]) {
logger.info("Cache hit!");
resolve(globalCache[cacheKey]);
return;
}
logger.info("Cache miss! Processing log...");
const chunks = chunkLogFile(logText);
logger.info(`Have ${chunks.length} chunks...`);
// Use only the last 3 chunks
const lastChunks = chunks.slice(-3);
try {
processChunks(lastChunks, platformIdentifier).then((errors) => {
let logSnip = "";
logger.info(`Found ${errors.length} errors`);
for (const error of errors) {
// Extract the start and end line indices from the error's relevant line range
const startLine = error.relevant_line_range[0] - 1; // Convert to zero-based index
const endLine = error.relevant_line_range[1]; // Convert to zero-based index
// Split the log text into lines
const logLines = logText.split('\n');
// Slice the relevant section of the log lines
let relevantSection = logLines.slice(startLine, endLine);
relevantSection.unshift("Possible context 1:")
// Limit each line in the relevant section to 350 characters. Snip out the middle and replace with '...'
relevantSection = relevantSection.map(line => {
if (line.length > 350) {
const snipStart = 150;
const snipEnd = line.length - 150;
return line.slice(0, snipStart) + '...(line truncated)...' + line.slice(snipEnd);
}
return line;
});
if (error.relevant_line_range[1] - error.relevant_line_range[0] < 3) {
// If the relevant section is too short, include the error_lines_text as well, in case the snipping was bad.
relevantSection.push("\nPossible context 2:");
relevantSection = relevantSection.concat(error.error_lines_text);
}
if (error.error_summary) {
logSnip += "\nError Summary:\n" + error.error_summary + '\n';
}
// Note if the error was infrastructure-related
if (error.is_infrastructure_error) {
relevantSection.unshift('This error is likely infrastructure-related:');
}
// Join the relevant section into a single string and append it to logSnip
logSnip += relevantSection.join('\n') + '\n';
if (error.stack_trace_crash_dump) {
if (error.failed_test_executable) {
logSnip += `\nStack trace for ${error.failed_test_executable}:\n`;
}
logSnip += error.stack_trace_crash_dump + '\n';
}
}
logger.info(logSnip);
globalCache[cacheKey] = { errors: errors, log: logSnip };
setTimeout(() => {
logger.info("Deleting cache entry...");
delete globalCache[cacheKey];
}, 240000);
resolve({ errors: errors, log: logSnip });
});
} catch (error) {
logger.info(`Error processing log: ${error}`);
reject(error);
}
});
}
module.exports = {
chunkLogFile,
snipTestFailureFromLog,
getAnalysis
};
|