545a83f108d3969962acc98451cca5fff1f5d07e
[WebKit.git] / Websites / perf.webkit.org / public / include / report-processor.php
1 <?php
2
3 require_once('../include/json-header.php');
4
5 class ReportProcessor {
6     private $db;
7     private $name_to_aggregator_id;
8     private $report_id;
9     private $runs;
10
11     function __construct($db) {
12         $this->db = $db;
13         $this->name_to_aggregator_id = array();
14     }
15
16     private function exit_with_error($message, $details = NULL) {
17         if (!$this->report_id) {
18             $details['failureStored'] = FALSE;
19             exit_with_error($message, $details);
20         }
21
22         $details['failureStored'] = $this->db->query_and_get_affected_rows(
23             'UPDATE reports SET report_failure = $1, report_failure_details = $2 WHERE report_id = $3',
24             array($message, $details ? json_encode($details) : NULL, $this->report_id)) == 1;
25         exit_with_error($message, $details);
26     }
27
28     function process($report, $existing_report_id = NULL) {
29         $this->report_id = $existing_report_id;
30         $this->runs = NULL;
31
32         array_key_exists('builderName', $report) or $this->exit_with_error('MissingBuilderName');
33         array_key_exists('buildTime', $report) or $this->exit_with_error('MissingBuildTime');
34
35         $builder_info = array('name' => $report['builderName']);
36         $slave_name = array_get($report, 'slaveName', NULL);
37         $slave_id = NULL;
38         if (!$existing_report_id) {
39             $hash = NULL;
40             if ($slave_name && array_key_exists('slavePassword', $report)) {
41                 $hash = hash('sha256', $report['slavePassword']);
42                 $slave = $this->db->select_first_row('build_slaves', 'slave', array('name' => $slave_name, 'password_hash' => $hash));
43                 if ($slave)
44                     $slave_id = $slave['slave_id'];
45             } else if (array_key_exists('builderPassword', $report))
46                 $hash = hash('sha256', $report['builderPassword']);
47
48             if (!$hash)
49                 $this->exit_with_error('BuilderNotFound');
50             if (!$slave_id)
51                 $builder_info['password_hash'] = $hash;
52         }
53
54         if (array_key_exists('builderPassword', $report))
55             unset($report['builderPassword']);
56         if (array_key_exists('slavePassword', $report))
57             unset($report['slavePassword']);
58
59         $builder_id = NULL;
60         if ($slave_id)
61             $builder_id = $this->db->select_or_insert_row('builders', 'builder', $builder_info);
62         else {
63             $builder = $this->db->select_first_row('builders', 'builder', $builder_info);
64             if (!$builder)
65                 $this->exit_with_error('BuilderNotFound', array('name' => $builder_info['name']));
66             $builder_id = $builder['builder_id'];
67             if ($slave_name)
68                 $slave_id = $this->db->select_or_insert_row('build_slaves', 'slave', array('name' => $slave_name));
69         }
70
71         $build_data = $this->construct_build_data($report, $builder_id, $slave_id);
72         if (!$existing_report_id)
73             $this->store_report($report, $build_data);
74
75         $this->ensure_aggregators();
76
77         $this->runs = new TestRunsGenerator($this->db, $this->name_to_aggregator_id, $this->report_id);
78         $this->recursively_ensure_tests($report['tests']);
79
80         $this->runs->aggregate();
81         $this->runs->compute_caches();
82
83         $platform_id = $this->db->select_or_insert_row('platforms', 'platform', array('name' => $report['platform']));
84         if (!$platform_id)
85             $this->exit_with_error('FailedToInsertPlatform', array('name' => $report['platform']));
86
87         // FIXME: Deprecate and unsupport "jobId".
88         $build_id = $this->resolve_build_id($build_data, array_get($report, 'revisions', array()),
89             array_get($report, 'jobId', array_get($report, 'buildRequest')));
90
91         $this->runs->commit($platform_id, $build_id);
92     }
93
94     private function construct_build_data($report, $builder_id, $slave_id) {
95         array_key_exists('buildNumber', $report) or $this->exit_with_error('MissingBuildNumber');
96         array_key_exists('buildTime', $report) or $this->exit_with_error('MissingBuildTime');
97
98         return array('builder' => $builder_id, 'slave' => $slave_id, 'number' => $report['buildNumber'], 'time' => $report['buildTime']);
99     }
100
101     private function store_report($report, $build_data) {
102         assert(!$this->report_id);
103         $this->report_id = $this->db->insert_row('reports', 'report', array(
104             'builder' => $build_data['builder'],
105             'slave' => $build_data['slave'],
106             'build_number' => $build_data['number'],
107             'content' => json_encode($report)));
108         if (!$this->report_id)
109             $this->exit_with_error('FailedToStoreRunReport');
110     }
111
112     private function ensure_aggregators() {
113         foreach (TestRunsGenerator::$aggregators as $name) {
114             $id = $this->db->select_or_insert_row('aggregators', 'aggregator', array('name' => $name));
115             if (!$id)
116                 $this->exit_with_error('FailedToInsertAggregator', array('aggregator' => $name));
117             $this->name_to_aggregator_id[$name] = $id;
118         }
119     }
120
121     private function resolve_build_id($build_data, $revisions, $build_request_id) {
122         // FIXME: This code has a race condition. See <rdar://problem/15876303>.
123         $results = $this->db->query_and_fetch_all("SELECT build_id, build_slave FROM builds
124             WHERE build_builder = $1 AND build_number = $2 AND build_time <= $3 AND build_time + interval '1 day' > $3",
125             array($build_data['builder'], $build_data['number'], $build_data['time']));
126         if ($results) {
127             $first_result = $results[0];
128             if ($first_result['build_slave'] != $build_data['slave'])
129                 $this->exit_with_error('MismatchingBuildSlave', array('storedBuild' => $results, 'reportedBuildData' => $build_data));
130             $build_id = $first_result['build_id'];
131         } else
132             $build_id = $this->db->insert_row('builds', 'build', $build_data);
133         if (!$build_id)
134             $this->exit_with_error('FailedToInsertBuild', $build_data);
135
136         if ($build_request_id) {
137             if ($this->db->update_row('build_requests', 'request', array('id' => $build_request_id), array('status' => 'completed', 'build' => $build_id))
138                 != $build_request_id)
139                 $this->exit_with_error('FailedToUpdateBuildRequest', array('buildRequest' => $build_request_id, 'build' => $build_id));
140         }
141
142
143         foreach ($revisions as $repository_name => $revision_data) {
144             $repository_id = $this->db->select_or_insert_row('repositories', 'repository', array('name' => $repository_name));
145             if (!$repository_id)
146                 $this->exit_with_error('FailedToInsertRepository', array('name' => $repository_name));
147
148             $commit_data = array('repository' => $repository_id, 'revision' => $revision_data['revision'], 'time' => array_get($revision_data, 'timestamp'));
149
150             $mismatching_commit = $this->db->query_and_fetch_all('SELECT * FROM build_commits, commits
151                 WHERE build_commit = commit_id AND commit_build = $1 AND commit_repository = $2 AND commit_revision != $3 LIMIT 1',
152                 array($build_id, $repository_id, $revision_data['revision']));
153             if ($mismatching_commit)
154                 $this->exit_with_error('MismatchingCommitRevision', array('build' => $build_id, 'existing' => $mismatching_commit, 'new' => $commit_data));
155
156             $commit_row = $this->db->select_or_insert_row('commits', 'commit',
157                 array('repository' => $repository_id, 'revision' => $revision_data['revision']), $commit_data, '*');
158             if (!$commit_row)
159                 $this->exit_with_error('FailedToRecordCommit', $commit_data);
160             if ($commit_data['time'] && abs($commit_row['commit_time'] - $commit_data['time']) > 1.0)
161                 $this->exit_with_error('MismatchingCommitTime', array('existing' => $commit_row, 'new' => $commit_data));
162
163             if (!$this->db->select_or_insert_row('build_commits', null,
164                 array('commit_build' => $build_id, 'build_commit' => $commit_row['commit_id']), null, '*'))
165                 $this->exit_with_error('FailedToRelateCommitToBuild', array('commit' => $commit_row, 'build' => $build_id));
166         }
167
168         return $build_id;
169     }
170
171     private function recursively_ensure_tests($tests, $parent_id = NULL, $level = 0) {
172         foreach ($tests as $test_name => $test) {
173             $test_id = $this->db->select_or_insert_row('tests', 'test', $parent_id ? array('name' => $test_name, 'parent' => $parent_id) : array('name' => $test_name),
174                 array('name' => $test_name, 'parent' => $parent_id, 'url' => array_get($test, 'url')));
175             if (!$test_id)
176                 $this->exit_with_error('FailedToAddTest', array('name' => $test_name, 'parent' => $parent_id));
177
178             if (array_key_exists('tests', $test))
179                 $this->recursively_ensure_tests($test['tests'], $test_id, $level + 1);
180
181             foreach (array_get($test, 'metrics', array()) as $metric_name => $aggregators_or_config_types) {
182                 $aggregators = $this->aggregator_list_if_exists($aggregators_or_config_types);
183                 if ($aggregators) {
184                     foreach ($aggregators as $aggregator_name)
185                         $this->runs->add_aggregated_metric($parent_id, $test_id, $test_name, $metric_name, $aggregator_name, $level);
186                 } else {
187                     $metric_id = $this->db->select_or_insert_row('test_metrics', 'metric', array('name' => $metric_name, 'test' => $test_id));
188                     if (!$metric_id)
189                         $this->exit_with_error('FailedToAddMetric', array('name' => $metric_name, 'test' => $test_id));
190
191                     foreach ($aggregators_or_config_types as $config_type => $values) {
192                         // Some tests submit groups of iterations; e.g. [[1, 2, 3, 4], [5, 6, 7, 8]]
193                         // Convert other tests to this format to simplify the computation later.
194                         if (gettype($values) !== 'array')
195                             $values = array($values);
196                         if (gettype($values[0]) !== 'array')
197                             $values = array($values);
198                         $this->runs->add_values_to_commit($metric_id, $config_type, $values);
199                         $this->runs->add_values_for_aggregation($parent_id, $test_name, $metric_name, $config_type, $values);
200                     }
201                 }
202             }
203         }
204     }
205
206     private function aggregator_list_if_exists($aggregators_or_config_types) {
207         if (array_key_exists(0, $aggregators_or_config_types))
208             return $aggregators_or_config_types;
209         else if (array_get($aggregators_or_config_types, 'aggregators'))
210             return $aggregators_or_config_types['aggregators'];
211         return NULL;
212     }
213 };
214
215 class TestRunsGenerator {
216     private $db;
217     private $name_to_aggregator_id;
218     private $report_id;
219     private $metrics_to_aggregate;
220     private $parent_to_values;
221     private $values_to_commit;
222
223     function __construct($db, $name_to_aggregator_id, $report_id) {
224         $this->db = $db;
225         $this->name_to_aggregator_id = $name_to_aggregator_id;
226         $this->report_id = $report_id;
227         $this->metrics_to_aggregate = array();
228         $this->parent_to_values = array();
229         $this->values_to_commit = array();
230     }
231
232     private function exit_with_error($message, $details = NULL) {
233         $details['failureStored'] = $this->db->query_and_get_affected_rows(
234             'UPDATE reports SET report_failure = $1, report_failure_details = $2 WHERE report_id = $3',
235             array($message, $details ? json_encode($details) : NULL, $this->report_id)) == 1;
236         exit_with_error($message, $details);
237     }
238
239     function add_aggregated_metric($parent_id, $test_id, $test_name, $metric_name, $aggregator_name, $level) {
240         array_key_exists($aggregator_name, $this->name_to_aggregator_id)
241             or $this->exit_with_error('AggregatorNotFound', array('name' => $aggregator_name));
242
243         $metric_id = $this->db->select_or_insert_row('test_metrics', 'metric', array('name' => $metric_name,
244             'test' => $test_id, 'aggregator' => $this->name_to_aggregator_id[$aggregator_name]));
245         if (!$metric_id)
246             $this->exit_with_error('FailedToAddAggregatedMetric', array('name' => $metric_name, 'test' => $test_id, 'aggregator' => $aggregator_name));
247
248         array_push($this->metrics_to_aggregate, array(
249             'test_id' => $test_id,
250             'parent_id' => $parent_id,
251             'metric_id' => $metric_id,
252             'test_name' => $test_name,
253             'metric_name' => $metric_name,
254             'aggregator' => $aggregator_name,
255             'level' => $level));
256     }
257
258     function add_values_for_aggregation($parent_id, $test_name, $metric_name, $config_type, $values, $aggregator = NULL) {
259         $value_list = &array_ensure_item_has_array(array_ensure_item_has_array(array_ensure_item_has_array(array_ensure_item_has_array(
260             $this->parent_to_values, strval($parent_id)), $metric_name), $config_type), $test_name);
261         array_push($value_list, array('aggregator' => $aggregator, 'values' => $values));
262     }
263
264     function aggregate() {
265         $expressions = array();
266         foreach ($this->metrics_to_aggregate as $test_metric) {
267             $configurations = array_get(array_get($this->parent_to_values, strval($test_metric['test_id']), array()), $test_metric['metric_name']);
268             foreach ($configurations as $config_type => $test_value_list) {
269                 // FIXME: We should preserve the test order. For that, we need a new column in our database.
270                 $values_by_iteration = $this->test_value_list_to_values_by_iterations($test_value_list, $test_metric, $test_metric['aggregator']);
271                 $flattened_aggregated_values = array();
272                 for ($i = 0; $i < count($values_by_iteration['values']); ++$i)
273                     array_push($flattened_aggregated_values, $this->aggregate_values($test_metric['aggregator'], $values_by_iteration['values'][$i]));
274
275                 $grouped_values = array();
276                 foreach ($values_by_iteration['group_sizes'] as $size) {
277                     $new_group = array();
278                     for ($i = 0; $i < $size; ++$i)
279                         array_push($new_group, array_shift($flattened_aggregated_values));
280                     array_push($grouped_values, $new_group);
281                 }
282
283                 $this->add_values_to_commit($test_metric['metric_id'], $config_type, $grouped_values);
284                 $this->add_values_for_aggregation($test_metric['parent_id'], $test_metric['test_name'], $test_metric['metric_name'],
285                     $config_type, $grouped_values, $test_metric['aggregator']);
286             }
287         }
288     }
289
290     private function test_value_list_to_values_by_iterations($test_value_list, $test_metric, $aggregator) {
291         $values_by_iterations = array();
292         $group_sizes = array();
293         $first_test = TRUE;
294         foreach ($test_value_list as $test_name => $aggregators_and_values) {
295             if (count($aggregators_and_values) == 1) // Either the subtest has exactly one aggregator or is raw value (not aggregated)
296                 $values = $aggregators_and_values[0]['values'];
297             else {
298                 $values = NULL;
299                 // Find the values of the subtest aggregated by the same aggregator.
300                 foreach ($aggregators_and_values as $aggregator_and_values) {
301                     if ($aggregator_and_values['aggregator'] == $aggregator) {
302                         $values = $aggregator_and_values['values'];
303                         break;                        
304                     }
305                 }
306                 if (!$values) {
307                     $this->exit_with_error('NoMatchingAggregatedValueInSubtest',
308                         array('parent' => $test_metric['test_id'],
309                         'metric' => $test_metric['metric_name'],
310                         'childTest' => $test_name,
311                         'aggregator' => $aggregator,
312                         'aggregatorAndValues' => $aggregators_and_values));
313                 }
314             }
315
316             for ($group = 0; $group < count($values); ++$group) {
317                 if ($first_test) {
318                     array_push($group_sizes, count($values[$group]));
319                     for ($i = 0; $i < count($values[$group]); ++$i)
320                         array_push($values_by_iterations, array());
321                 }
322
323                 if ($group_sizes[$group] != count($values[$group])) {
324                     $this->exit_with_error('IterationGroupSizeIsInconsistent',
325                         array('parent' => $test_metric['test_id'],
326                         'metric' => $test_metric['metric_name'],
327                         'childTest' => $test_name,
328                         'groupSizes' => $group_sizes,
329                         'group' => $group,
330                         'values' => $values));
331                 }
332             }
333             $first_test = FALSE;
334
335             if (count($values) != count($group_sizes)) {
336                 // FIXME: We should support bootstrapping or just computing the mean in this case.
337                 $this->exit_with_error('IterationGroupCountIsInconsistent', array('parent' => $test_metric['test_id'],
338                     'metric' => $test_metric['metric_name'], 'childTest' => $test_name,
339                     'valuesByIterations' => $values_by_iterations, 'values' => $values));
340             }
341
342             $flattened_iteration_index = 0;
343             for ($group = 0; $group < count($values); ++$group) {
344                 for ($i = 0; $i < count($values[$group]); ++$i) {
345                     $run_iteration_value = $values[$group][$i];
346                     if (!is_numeric($run_iteration_value)) {
347                         $this->exit_with_error('NonNumeralIterationValueForAggregation', array('parent' => $test_metric['test_id'],
348                             'metric' => $test_metric['metric_name'], 'childTest' => $test_name,
349                             'valuesByIterations' => $values_by_iterations, 'values' => $values, 'index' => $i));
350                     }
351                     array_push($values_by_iterations[$flattened_iteration_index], $run_iteration_value);
352                     $flattened_iteration_index++;
353                 }
354             }
355         }
356
357         if (!$values_by_iterations)
358             $this->exit_with_error('NoIterationToAggregation', array('parent' => $test_metric['test_id'], 'metric' => $test_metric['metric_name']));
359
360         return array('values' => $values_by_iterations, 'group_sizes' => $group_sizes);
361     }
362
363     static public $aggregators = array('Arithmetic', 'Geometric', 'Harmonic', 'Total');
364
365     private function aggregate_values($aggregator, $values) {
366         switch ($aggregator) {
367         case 'Arithmetic':
368             return array_sum($values) / count($values);
369         case 'Geometric':
370             return exp(array_sum(array_map(function ($x) { return log($x); }, $values)) / count($values));
371         case 'Harmonic':
372             return count($values) / array_sum(array_map(function ($x) { return 1 / $x; }, $values));
373         case 'Total':
374             return array_sum($values);
375         case 'SquareSum': # This aggregator is only used internally to compute run_square_sum_cache in test_runs table.
376             return array_sum(array_map(function ($x) { return $x * $x; }, $values));
377         default:
378             $this->exit_with_error('UnknownAggregator', array('aggregator' => $aggregator));
379         }
380         return NULL;
381     }
382
383     function compute_caches() {
384         $expressions = array();
385         $size = count($this->values_to_commit);
386         for ($i = 0; $i < $size; ++$i) {
387             $flattened_value = array();
388             foreach ($this->values_to_commit[$i]['values'] as $group) {
389                 for ($j = 0; $j < count($group); ++$j) {
390                     $iteration_value = $group[$j];
391                     if (gettype($iteration_value) === 'array') { // [relative time, value]
392                         if (count($iteration_value) != 2) {
393                             // FIXME: Also report test and metric.
394                             $this->exit_with_error('InvalidIterationValueFormat', array('values' => $this->values_to_commit[$i]['values']));
395                         }
396                         $iteration_value = $iteration_value[1];
397                     }
398                     array_push($flattened_value, $iteration_value);                    
399                 }
400             }
401             $this->values_to_commit[$i]['mean'] = $this->aggregate_values('Arithmetic', $flattened_value);
402             $this->values_to_commit[$i]['sum'] = $this->aggregate_values('Total', $flattened_value);
403             $this->values_to_commit[$i]['square_sum'] = $this->aggregate_values('SquareSum', $flattened_value);
404         }
405     }
406
407     function add_values_to_commit($metric_id, $config_type, $values) {
408         array_push($this->values_to_commit, array('metric_id' => $metric_id, 'config_type' => $config_type, 'values' => $values));
409     }
410
411     function commit($platform_id, $build_id) {
412         $this->db->begin_transaction() or $this->exit_with_error('FailedToBeginTransaction');
413
414         foreach ($this->values_to_commit as $item) {
415             $config_data = array('metric' => $item['metric_id'], 'type' => $item['config_type'], 'platform' => $platform_id);
416             $config_id = $this->db->select_or_insert_row('test_configurations', 'config', $config_data);
417             if (!$config_id)
418                 $this->rollback_with_error('FailedToObtainConfiguration', $config_data);
419
420             $values = $item['values'];
421             $total_count = 0;
422             for ($group = 0; $group < count($values); ++$group)
423                 $total_count += count($values[$group]);
424             $run_data = array('config' => $config_id, 'build' => $build_id, 'iteration_count_cache' => $total_count,
425                 'mean_cache' => $item['mean'], 'sum_cache' => $item['sum'], 'square_sum_cache' => $item['square_sum']);
426             $run_id = $this->db->insert_row('test_runs', 'run', $run_data);
427             if (!$run_id)
428                 $this->rollback_with_error('FailedToInsertRun', array('metric' => $item['metric_id'], 'param' => $run_data));
429
430             $flattened_order = 0;
431             for ($group = 0; $group < count($values); ++$group) {
432                 for ($i = 0; $i < count($values[$group]); ++$i) {
433                     $iteration_value = $values[$group][$i];
434                     $relative_time = NULL;
435                     if (gettype($iteration_value) === 'array') {
436                         assert(count($iteration_value) == 2); // compute_caches checks this condition.
437                         $relative_time = $iteration_value[0];
438                         $iteration_value = $iteration_value[1];
439                     }
440                     $param = array('run' => $run_id, 'order' => $flattened_order, 'value' => $iteration_value,
441                         'group' => count($values) == 1 ? NULL : $group, 'relative_time' => $relative_time);
442                     $this->db->insert_row('run_iterations', 'iteration', $param, NULL)
443                         or $this->rollback_with_error('FailedToInsertIteration', array('config' => $config_id, 'build' => $build_id, 'param' => $param));
444                     $flattened_order++;
445                 }
446             }
447         }
448
449         $this->db->query_and_get_affected_rows("UPDATE reports
450             SET (report_committed_at, report_build) = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC', $2)
451             WHERE report_id = $1", array($this->report_id, $build_id));
452
453         $this->db->commit_transaction() or $this->exit_with_error('FailedToCommitTransaction');
454     }
455
456     private function rollback_with_error($message, $details) {
457         $this->db->rollback_transaction();
458         $this->exit_with_error($message, $details);
459     }
460 };
461
462 ?>