-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathbenchUtil.py
More file actions
1909 lines (1600 loc) · 65.5 KB
/
benchUtil.py
File metadata and controls
1909 lines (1600 loc) · 65.5 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
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
import types
import re
import time
import traceback
import os
import pwd
import shutil
import sys
try:
import cPickle as pickle # python2
except ImportError:
import pickle
import datetime
import constants
import common
import random
import signal
import QPSChart
import IndexChart
import subprocess
import shlex
import statistics
import ps_head
try:
import distutils
PERF_EXE = distutils.spawn.find_executable('perf')
except:
PERF_EXE = None
if PERF_EXE is None:
print(f'no perf executable; will not collect aggregate CPU profiling data')
else:
print(f'perf executable is {PERF_EXE}; will collect aggregate CPU profiling data')
PYTHON_MAJOR_VER = sys.version_info.major
VMSTAT_PATH = shutil.which('vmstat')
if PYTHON_MAJOR_VER < 3:
raise RuntimeError('Please run with Python 3.x! Got: %s' % str(sys.version))
# Skip the first N runs of a given category (cold) or particular task (hot):
WARM_SKIP = 3
# Skip this pctg of the slowest runs:
SLOW_SKIP_PCT = 10
# Disregard first N seconds of query tasks for computing avg QPS:
DISCARD_QPS_WARMUP_SEC = 5
# From the N times we run each task in a single JVM, how do we pick
# the single QPS to represent those results:
# SELECT = 'min'
# SELECT = 'mean'
SELECT = 'median'
MAX_SCORE_DIFF = .00001
VERBOSE = False
DO_PERF = constants.DO_PERF
PERF_STATS = constants.PERF_STATS
osName = common.osName
# returns an array of all java files in a directory; walks the directory tree
def addFiles(root):
files = []
for f in os.listdir(root):
f = os.path.join(root, f).replace("\\","/")
if os.path.isdir(f):
files.extend(addFiles(f))
elif not f.startswith('.#') and f.endswith('.java'):
files.append(f)
return files
def htmlColor(v):
if v < 0:
return colorFormat(-v, 'html', 'red')
else:
return colorFormat(v, 'html', 'green')
def htmlColor2(v):
vstr = '%.1f X' % v
if v < 1.0:
return colorFormat(vstr, 'html', 'red')
else:
return colorFormat(vstr, 'html', 'green')
def jiraColor(v):
if v < 0:
return colorFormat(-v, 'jira', 'red')
else:
return colorFormat(v, 'jira', 'green')
def pValueColor(v, form):
vstr = '%.3f' % v
if v <= 0.05:
return colorFormat(vstr, form, 'green')
else:
return colorFormat(vstr, form, 'red')
def colorFormat(value, form, color):
if form == 'html':
return '<font color="{}">{}</font>'.format(color, value)
elif form == 'jira':
return '{{color:{}}}{}{{color}}'.format(color, value)
else:
raise RuntimeException("unknown format {}".format(form))
def getArg(argName, default, hasArg=True):
try:
idx = sys.argv.index(argName)
except ValueError:
v = default
else:
if hasArg:
v = sys.argv[idx+1]
del sys.argv[idx:idx+2]
try:
sys.argv.index(argName)
except ValueError:
# ok
pass
else:
raise RuntimeError('argument %s appears more than once' % argName)
else:
v = True
del sys.argv[idx]
return v
def get_username():
uid = os.getuid()
return pwd.getpwuid(uid).pw_name
def checkoutToName(checkout):
return checkout.split('/')[-1]
def checkoutToPath(checkout):
return checkout if '/' in checkout else '%s/%s' % (constants.BASE_DIR, checkout)
def checkoutToBenchPath(checkout):
return '%s/lucene/benchmark' % checkoutToPath(checkout)
def checkoutToUtilPath(checkout):
p = checkoutToPath(checkout)
if os.path.exists('%s/luceneutil' % p):
# This checkout has a 'private' luceneutil:
compPath = '%s/luceneutil' % p
else:
compPath = constants.BENCH_BASE_DIR
return compPath
def nameToIndexPath(name):
return '%s/%s' % (constants.INDEX_DIR_BASE, name)
def decode(str_or_bytes):
if PYTHON_MAJOR_VER < 3 or isinstance(str_or_bytes, str):
return str_or_bytes
else:
return str_or_bytes.decode('utf-8')
class SearchTask:
# TODO: subclass SearchGroupTask
countOnlyCount = None
isCountOnly = False
def verifySame(self, other, verifyScores, verifyCounts):
if re.match('.*Knn(Float|Byte)VectorQuery:', self.query) is not None:
# While KNN search is statically randomized (seed 42?), the concurrent HNSW merge alters the order of results
return
if not isinstance(other, SearchTask):
self.fail('not a SearchTask (%s)' % other)
if self.query != other.query:
self.fail('wrong query: %s vs %s' % (self.query, other.query))
if self.sort != other.sort:
self.fail('wrong sort: %s vs %s' % (self.sort, other.sort))
if self.groupField is None:
if False:
# TODO: fix SearchPerfTest -- cannot use term count across threads since mutiple threads store in the query
if self.expandedTermCount != other.expandedTermCount:
print('WARNING: expandedTermCounts differ for %s: %s vs %s' % (self, self.expandedTermCount, other.expandedTermCount))
# self.fail('wrong expandedTermCount: %s vs %s' % (self.expandedTermCount, other.expandedTermCount))
if verifyCounts:
if self.hitCount != other.hitCount:
self.fail('wrong hitCount: %s vs %s' % (self.hitCount, other.hitCount))
if self.countOnlyCount != other.countOnlyCount:
self.fail('wrong countOnlyCount: %s vs %s' % (self.countOnlyCount, other.coutnOnlyCount))
if len(self.hits) != len(other.hits):
self.fail('wrong top hit count: %s vs %s' % (len(self.hits), len(other.hits)))
if verifyScores:
# Collapse equals... this is sorta messy, but necessary because we
# do not dedup by true id in SearchPerfTest
hitsSelf = collapseDups(self.hits)
hitsOther = collapseDups(other.hits)
if verifyCounts and len(hitsSelf) != len(hitsOther):
self.fail('self=%s: wrong collapsed hit count: %s vs %s\n %s vs %s\n %s vs %s' % (self, len(hitsSelf), len(hitsOther), hitsSelf, hitsOther, self.hits, other.hits))
if verifyScores:
for i in range(len(hitsSelf)):
if hitsSelf[i][1] != hitsOther[i][1]:
if False:
if abs(float(hitsSelf[i][1])-float(hitsOther[i][1])) > MAX_SCORE_DIFF:
self.fail('hit %s has wrong field/score value %s vs %s' % (i, hitsSelf[i][1], hitsOther[i][1]))
else:
print('WARNING: query=%s filter=%s sort=%s: slight score diff %s vs %s' % \
(self.query, self.filter, self.sort, hitsSelf[i][1], hitsOther[i][1]))
else:
self.fail('hit %s has wrong field/score value %s vs %s' % (i, hitsSelf[i], hitsOther[i]))
if hitsSelf[i][0] != hitsOther[i][0] and i < len(hitsSelf)-1:
self.fail('hit %s has wrong id/s %s vs %s' % (i, hitsSelf[i], hitsOther[i]))
else:
# groups
if self.groupCount != other.groupCount:
self.fail('wrong groupCount: cat=%s groupField=%s %s vs %s: self=%s, other=%s' % (self.cat, self.groupField, self.groupCount, other.groupCount, self, other))
for groupIDX in range(self.groupCount):
groupValue1, groupTotHits1, groupTopScore1, groups1 = self.groups[groupIDX]
groupValue2, groupTotHits2, groupTopScore2, groups2 = other.groups[groupIDX]
# TODO: if we have 1 pass and 2 pass on the "same" group field, assert same
# TODO: this is because block grouping doesn't pull group
# values; conditionalize this on block grouping
if False and groupValue1 != groupValue2:
self.fail('group %d has wrong groupValue: %s vs %s' % (groupIDX, groupValue1, groupValue2))
# iffy: this is a float cmp
if verifyScores:
if groupTopScore1 != groupTopScore2:
self.fail('group %d has wrong groupTopScore: %s vs %s' % (groupIDX, groupTopScore1, groupTopScore2))
if groupTotHits1 != groupTotHits2:
self.fail('group %d has wrong totHits: %s vs %s' % (groupIDX, groupTotHits1, groupTotHits2))
if len(groups1) != len(groups2):
self.fail('group %d has wrong number of docs: %s vs %s' % (groupIDX, len(groups1), len(groups2)))
groups1 = collapseDups(groups1)
groups2 = collapseDups(groups2)
for docIDX in range(len(groups1)):
if groups1[docIDX][1] != groups2[docIDX][1]:
self.fail('hit %s has wrong field/score value %s vs %s' % (docIDX, groups1[docIDX][1], groups2[docIDX][1]))
if groups1[docIDX][0] != groups2[docIDX][0] and docIDX < len(groups1)-1:
self.fail('hit %s has wrong id/s %s vs %s' % (docIDX, groups1[docIDX][0], groups2[docIDX][0]))
if self.facets != other.facets:
if False:
print()
print('***WARNING*** facet diffs: %s: %s vs %s'% (self, self.facets, other.facets))
print()
else:
self.fail('facets differ: %s vs %s' % (self.facets, other.facets))
def fail(self, message):
s = 'query=%s filter=%s sort=%s groupField=%s hitCount=%s' % (self.query, self.filter, self.sort, self.groupField, self.hitCount)
raise RuntimeError('%s: %s' % (s, message))
def __str__(self):
s = self.query
if self.isCountOnly:
s += ' [count-only]'
else:
if self.sort is not None:
s += ' [sort=%s]' % self.sort
if self.groupField is not None:
s += ' [groupField=%s]' % self.groupField
if self.facets is not None:
s += ' [facets=%s]' % self.facets
return s
def __eq__(self, other):
if not isinstance(other, SearchTask):
return False
else:
return self.query == other.query and \
self.sort == other.sort and \
self.groupField == other.groupField and \
self.filter == other.filter and \
self.facets == other.facets and \
self.isCountOnly == other.isCountOnly
def __hash__(self):
return hash(self.query) + hash(self.sort) + hash(self.groupField) + hash(self.filter) + hash(type(self.facets)) + hash(self.isCountOnly)
class RespellTask:
cat = 'Respell'
def verifySame(self, other, verifyScores, verifyCounts):
if not isinstance(other, RespellTask):
self.fail('not a RespellTask')
if self.term != other.term:
self.fail('wrong term: %s vs %s' % (self.term, other.term))
if self.hits != other.hits:
self.fail('wrong hits: %s vs %s' % (self.hits, other.hits))
def fail(self, message):
raise RuntimeError('respell: term=%s: %s' % (self.term, message))
def __str__(self):
return 'Respell %s' % self.term
def __eq__(self, other):
if not isinstance(other, RespellTask):
return False
else:
return self.term == other.term
def __hash__(self):
return hash(self.term)
class PKLookupTask:
cat = 'PKLookup'
def verifySame(self, other, verifyScores, verifyCounts):
# already "verified" in search perf test, ie, that the docID
# returned in fact has the id that was asked for
pass
def __str__(self):
return 'PK%s' % self.pkOrd
def __eq__(self, other):
if not isinstance(other, PKLookupTask):
return False
else:
return self.pkOrd == other.pkOrd
def __hash__(self):
return hash(self.pkOrd)
class PKLookupWithTermStateTask:
cat = 'PKLookupWithTermState'
def verifySame(self, other, verifyScores, verifyCounts):
# already "verified" in search perf test, ie, that the docID
# returned in fact has the id that was asked for
pass
def __str__(self):
return 'PKTS%s' % self.pkOrd
def __eq__(self, other):
if not isinstance(other, PKLookupWithTermStateTask):
return False
else:
return self.pkOrd == other.pkOrd
def __hash__(self):
return hash(self.pkOrd)
class PointsPKLookupTask:
cat = 'PointsPKLookup'
def verifySame(self, other, verifyScores, verifyCounts):
# already "verified" in search perf test, ie, that the docID
# returned in fact has the id that was asked for
pass
def __str__(self):
return 'PointsPK%s' % self.pkOrd
def __eq__(self, other):
if not isinstance(other, PointsPKLookupTask):
return False
else:
return self.pkOrd == other.pkOrd
def __hash__(self):
return hash(self.pkOrd)
def collapseDups(hits):
newHits = []
for id, v in hits:
if len(newHits) == 0 or v != newHits[-1][1]:
newHits.append(([id], v))
else:
newHits[-1][0].append(id)
newHits[-1][0].sort()
return newHits
reSearchTaskOld = re.compile('cat=(.*?) q=(.*?) s=(.*?) group=null hits=(null|[0-9]+\\+?) facets=(.*?)$')
reSearchGroupTaskOld = re.compile('cat=(.*?) q=(.*?) s=(.*?) group=(.*?) groups=(.*?) hits=([0-9]+\\+?) groupTotHits=([0-9]+)(?: totGroupCount=(.*?))? facets=(.*?)$', re.DOTALL)
reSearchTask = re.compile('cat=(.*?) q=(.*?) s=(.*?) f=(.*?) group=null hits=(null|[0-9]+\\+?)$')
reSearchGroupTask = re.compile('cat=(.*?) q=(.*?) s=(.*?) f=(.*?) group=(.*?) groups=(.*?) hits=([0-9]+\\+?) groupTotHits=([0-9]+)(?: totGroupCount=(.*?))?$', re.DOTALL)
reCountOnlyTask = re.compile('cat=(.*?) q=(.*?) countOnlyCount=(.*?)?$', re.DOTALL)
reSearchHitScore = re.compile('doc=(.*?) score=(.*?)$')
reSearchHitField = re.compile('doc=(.*?) .*?=(.*?)$')
reRespellHit = re.compile('(.*?) freq=(.*?) score=(.*?)$')
rePKOrd = re.compile(r'PK(?:TS)?(.*?)\[')
reOneGroup = re.compile('group=(.*?) totalHits=(.*?)(?: hits)? groupRelevance=(.*?)$', re.DOTALL)
reHeap = re.compile('HEAP: ([0-9]+)$')
reLatencyAndStartTime = re.compile(r'^([\d.]+) msec @ ([\d.]+) msec$')
reTasksWinddown = re.compile('^Start of tasks winddown: ([0-9.]+) msec$')
reAvgCPUCores = re.compile('^Average CPU cores used: (-?[0-9.]+)$')
def parse_times_line(task, line):
m = reLatencyAndStartTime.match(line.decode('utf-8'))
if m is None:
raise RuntimeError(f'unable to parse {line} into latency & start time')
task.msec = float(m.group(1))
task.startMsec = float(m.group(2))
def parseResults(resultsFiles):
taskIters = []
heaps = []
for resultsFile in resultsFiles:
tasks = []
if not os.path.exists(resultsFile):
# nocommit -- why would we pass this file in, if it does not exist?
continue
if os.path.exists(resultsFile + '.stdout') and os.path.getsize(resultsFile + '.stdout') > 50*1024:
raise RuntimeError('%s.stdout is %d bytes; leftover System.out.println?' % (resultsFile, os.path.getsize(resultsFile + '.stdout')))
tasksWindownMS = -1
avgCPUCores = -1
# print 'parse %s' % resultsFile
f = open(resultsFile, 'rb')
while True:
line = f.readline()
if line == b'':
break
line = line.strip()
if line.startswith(b'Start of tasks winddown: '):
tasksWindownMS = float(reTasksWinddown.match(line.decode('utf-8')).group(1))
continue
if line.startswith(b'Average CPU cores used: '):
avgCPUCores = float(reAvgCPUCores.match(line.decode('utf-8')).group(1))
continue
if line.startswith(b'HEAP: '):
m = reHeap.match(decode(line))
heaps.append(int(m.group(1)))
if line.startswith(b'TASK: cat='):
task = SearchTask()
parse_times_line(task, f.readline().strip())
task.threadID = int(f.readline().strip().split()[1])
task.facets = None
m = reSearchTask.match(decode(line[6:]))
if m is not None:
cat, task.query, sort, filter, hitCount = m.groups()
else:
m = reSearchTaskOld.match(decode(line[6:]))
if m is not None:
cat, task.query, sort, hitCount, facets = m.groups()
filter = None
else:
m = reCountOnlyTask.search(decode(line))
if m is not None:
cat = m.group(1)
task.query = m.group(2)
task.isCountOnly = True
task.countOnlyCount = int(m.group(3))
hitCount = None
filter = None
sort = 'null'
else:
cat = None
if cat is not None:
task.cat = cat
task.groups = None
task.groupField = None
task.filter = filter
# print 'CAT %s' % cat
if hitCount == 'null':
task.hitCount = "0"
else:
task.hitCount = hitCount
if sort in ('<string: "title">', '<string: "titleDV">', '<sortedset: "title"> selector=MIN'):
task.sort = 'Title'
elif sort.startswith('<long: "datenum">') or sort.startswith('<long: "lastModNDV">') or sort.startswith('<sortednumeric: "lastMod"> selector=MIN type=LONG'):
task.sort = 'DateTime'
elif sort in ('<string: "month">', '<string: "monthSortedDV">', '<sortedset: "month"> selector=MIN'):
task.sort = 'Month'
elif sort == '<int: "dayOfYearNumericDV">' or sort.startswith('<sortednumeric: "dayOfYear"> selector=MIN type=INT'):
task.sort = 'DayOfYear'
elif sort == '<string_val: "titleBDV">':
task.sort = 'TitleBinary'
elif sort != 'null':
raise RuntimeError('could not parse sort: %s' % sort)
else:
task.sort = None
task.hits = []
task.expandedTermCount = 0
while True:
line = f.readline().strip()
if line == b'':
break
if task.facets is not None:
task.facets.append(line)
continue
if line.find(b'expanded terms') != -1:
task.expandedTermCount = int(line.split()[0])
continue
if line.find(b'Zing VM Warning') != -1:
continue
if line.find(b'facets') != -1:
task.facets = []
continue
if line.find(b'hilite time') != -1:
task.hiliteMsec = float(line.split()[2])
continue
if line.find(b'getFacetResults time') != -1:
task.getFacetResultsMsec = float(line.split()[2])
continue
if line.startswith(b'HEAP: '):
m = reHeap.match(decode(line))
heaps.append(int(m.group(1)))
break
if sort == 'null':
m = reSearchHitScore.match(decode(line))
id = int(m.group(1))
score = m.group(2)
# score stays a string so we can do "precise" ==
task.hits.append((id, score))
else:
m = reSearchHitField.match(decode(line))
id = int(m.group(1))
field = m.group(2)
task.hits.append((id, field))
else:
m = reSearchGroupTask.match(decode(line[6:]))
if m is not None:
cat, task.query, sort, filter, task.groupField, groupCount, hitCount, groupedHitCount, totGroupCount = m.groups()
else:
m = reSearchGroupTaskOld.match(decode(line[6:]))
if m is not None:
cat, task.query, sort, task.groupField, groupCount, hitCount, groupedHitCount, totGroupCount, facets = m.groups()
filter = None
if cat is not None:
task.cat = cat
task.hits = hitCount
task.hitCount = hitCount
task.groupedHitCount = groupedHitCount
task.groupCount = int(groupCount)
task.filter = filter
if totGroupCount in (None, 'null'):
task.totGroupCount = None
else:
task.totGroupCount = int(totGroupCount)
# TODO: handle different sorts
task.sort = None
task.groups = []
group = None
while True:
line = f.readline().strip()
if line == b'':
break
if line.find(b'Zing VM Warning') != -1:
continue
if line.startswith(b'HEAP: '):
m = reHeap.match(decode(line))
heaps.append(int(m.group(1)))
break
m = reOneGroup.search(decode(line))
if m is not None:
groupValue, groupTotalHits, groupTopScore = m.groups()
group = (groupValue, int(groupTotalHits), float(groupTopScore), [])
task.groups.append(group)
continue
m = reSearchHitScore.search(decode(line))
if m is not None:
doc = int(m.group(1))
score = float(m.group(2))
group[-1].append((doc, score))
else:
# BUG
raise RuntimeError('result parsing failed: line=%s' % line)
elif line.find(b'Zing VM Warning') != -1:
continue
else:
raise RuntimeError('result parsing failed: line=%s' % line)
elif line.startswith(b'TASK: respell'):
task = RespellTask()
parse_times_line(task, f.readline().strip())
task.threadID = int(f.readline().strip().split()[1])
task.term = line[14:]
task.hits = []
while True:
line = f.readline().strip()
if line == b'':
break
if line.find(b'Zing VM Warning') != -1:
continue
if line.startswith(b'HEAP: '):
m = reHeap.match(decode(line))
heaps.append(int(m.group(1)))
break
m = reRespellHit.search(decode(line))
suggest, freq, score = m.groups()
task.hits.append((suggest, int(freq), float(score)))
elif line.startswith(b'TASK: PKTS'):
task = PKLookupWithTermStateTask()
task.pkOrd = rePKOrd.search(decode(line)).group(1)
parse_times_line(task, f.readline().strip())
task.threadID = int(f.readline().strip().split()[1])
elif line.startswith(b'TASK: PK'):
task = PKLookupTask()
task.pkOrd = rePKOrd.search(decode(line)).group(1)
parse_times_line(task, f.readline().strip())
task.threadID = int(f.readline().strip().split()[1])
elif line.startswith(b'TASK: PointsPK'):
task = PointsPKLookupTask()
task.pkOrd = rePKOrd.search(decode(line)).group(1)
parse_times_line(task, f.readline().strip())
task.threadID = int(f.readline().strip().split()[1])
else:
task = None
if line.find(b'\tat') != -1:
raise RuntimeError('log has exceptions')
if task is not None:
tasks.append(task)
taskIters.append(tasks)
if tasksWindownMS == -1:
raise RuntimeError(f'did not find "Start of tasks winddown: " line in results file {resultsFile}')
# TODO: why are we returning tasksWindownMS (which is per-result-file) here when
# we were given multiple results files?
return taskIters, heaps, tasksWindownMS, avgCPUCores
# Collect task latencies segregated by categories across all the runs of the task
# This allows calculating P50, P90, P99 and P100 latencies per task
def collateTaskLatencies(resultIters):
iters = []
for results in resultIters:
byCat = {}
iters.append(byCat)
for task in results:
if isinstance(task, SearchTask):
key = (task.cat, task.sort)
else:
key = (task.cat,)
if key not in byCat:
byCat[key] = ([])
l = byCat[key]
l.append(task.msec)
return iters
def collateResults(resultIters):
iters = []
for results in resultIters:
# Keyed first by category (Fuzzy1, Respell, ...) and 2nd be exact
# task mapping to list of runs of that task. For a cold run (no task repeats)
# the 2nd map will always map to a length-1 list.
byCat = {}
iters.append(byCat)
for task in results:
if isinstance(task, SearchTask):
key = (task.cat, task.sort)
else:
key = (task.cat,)
if key not in byCat:
byCat[key] = ([], {})
l, d = byCat[key]
l.append(task)
if task not in d:
d[task] = [task]
else:
d[task].append(task)
return iters
def agg(iters, cat, name, verifyCounts):
bestAvgMS = None
lastHitCount = None
accumMS = []
totHitCount = 0
# Iterate over each JVM instance we ran
for tasksByCat in iters:
# Maps cat -> actual tasks ran
if cat not in tasksByCat:
continue
tasks = tasksByCat[cat]
if len(tasks[0]) <= WARM_SKIP:
raise RuntimeError('only %s tasks in cat %s' % (len(tasks[0]), cat))
totHitCount = 0
totCountOnlyCount = 0
count = 0
sumMS = 0.0
if VERBOSE:
print('AGG: cat=%s' % str(cat))
# Iterate over each category's instances, eg a given category
# might have 5 different instances:
for task, results in tasks[1].items():
allMS = [result.msec for result in results]
if VERBOSE:
print(' %s' % task)
print(' before prune:')
for t in allMS:
print(' %.4f' % t)
if len(allMS) <= WARM_SKIP:
raise RuntimeError(f'only {len(allMS)} runs (<= warmup={WARM_SKIP}) in cat {cat} for task {task}')
# Skip warmup runs
allMS = allMS[WARM_SKIP:]
allMS.sort()
minMS = allMS[0]
if VERBOSE:
print(' after sort:')
for t in allMS:
print(' %.4f' % t)
# Skip slowest SLOW_SKIP_PCT runs:
skipSlowest = int(len(allMS)*SLOW_SKIP_PCT/100.)
if VERBOSE:
print('skipSlowest %s' % skipSlowest)
if skipSlowest > 0:
pruned = allMS[:-skipSlowest]
else:
pruned = allMS
if VERBOSE:
print(' after prune:')
for t in pruned:
print(' %.4f' % t)
if SELECT == 'min':
sumMS += minMS
count += 1
elif SELECT == 'mean':
sumMS += sum(pruned)
count += len(pruned)
elif SELECT == 'median':
mid = len(pruned) // 2
if len(pruned) % 2 == 0:
median = (pruned[mid-1] + pruned[mid])/2.0
else:
median = pruned[mid]
if VERBOSE:
print(' median %.4f' % median)
sumMS += median
count += 1
else:
raise RuntimeError('unrecognized SELECT=%s: should be min, median or mean' % SELECT)
if isinstance(task, SearchTask):
if task.countOnlyCount is not None:
totCountOnlyCount += task.countOnlyCount
elif task.groupField is None:
totHitCount = sum_hit_count(totHitCount, task.hitCount)
else:
for group in task.groups:
totHitCount += group[1]
# AvgMS per query in category, eg if we ran 5 different queries in
# each cat, then this is AvgMS for query in that cat:
avgMS = sumMS/count
accumMS.append(avgMS)
if lastHitCount is None:
lastHitCount = totHitCount
lastCountOnlyCount = totCountOnlyCount
elif verifyCounts:
if totHitCount != lastHitCount:
raise RuntimeError('different hit counts: %s vs %s' % (lastHitCount, totHitCount))
if totCountOnlyCount != lastCountOnlyCount:
raise RuntimeError('different count only counts: %s vs %s' % (lastCountOnlyCount, totCountOnlyCount))
if VERBOSE:
#accumMS.sort()
minValue = min(accumMS)
#print ' accumMS=%s' % ' '.join(['%5.1f' % x for x in accumMS])
print(' %s %s: accumMS=%s' % (name, cat[0], ' '.join(['%5.1f' % (100.0*(x-minValue)/minValue) for x in accumMS])))
return accumMS, totHitCount
def sum_hit_count(hc1, hc2):
lower_bound = False
_type = basestring if PYTHON_MAJOR_VER < 3 else str
if isinstance(hc1, _type) and hc1.endswith('+'):
lower_bound = True
hc1 = int(hc1[:-1])
else:
hc1 = int(hc1)
if isinstance(hc2, _type) and hc2.endswith('+'):
lower_bound = True
hc2 = int(hc2[:-1])
else:
hc2 = int(hc2)
return str(hc1+hc2) + (lower_bound and "+" or "")
def stats(l):
# min, max, mean, stddev
if len(l) == 0:
return 0.0, 0.0, 0.0, 0.0
else:
mu = statistics.mean(l)
return min(l), max(l), mu, statistics.stdev(l) if len(l) > 1 else 0
def run(cmd, logFile=None, indent=' ', vmstatLogFile=None, topLogFile=None):
print('%srun: %s, cwd=%s' % (indent, cmd, os.getcwd()))
if logFile is not None:
out = open(logFile, 'wb')
else:
out = subprocess.STDOUT
if vmstatLogFile is not None:
vmstatCmd = f'{VMSTAT_PATH} --active --wide --timestamp --unit M 1 > {vmstatLogFile} 2>&1 &'
print(f'run vmstat: {vmstatCmd}')
vmstatProcess = subprocess.Popen(vmstatCmd, shell=True, preexec_fn=os.setsid)
if topLogFile is not None:
topProcess = ps_head.PSTopN(10, topLogFile)
print(f'run {topProcess.cmd} to {topLogFile}')
p = subprocess.Popen(cmd, stdout=out, stderr=out)
if p.wait():
if logFile is not None and os.path.getsize(logFile) < 50*1024:
print(open(logFile).read())
raise RuntimeError('failed: %s [wd %s]; see logFile %s' % (cmd, os.getcwd(), logFile))
if vmstatLogFile is not None:
print(f'now kill vmstat: pid={vmstatProcess.pid}')
# TODO: messy! can we get process group working so we can kill bash and its child reliably?
subprocess.check_call(['pkill', '-u', get_username(), 'vmstat'])
# os.kill(vmstatProcess.pid, signal.SIGKILL)
if vmstatProcess.poll() is None:
raise RuntimeError('failed to kill vmstat child process? pid={vmstatProcess.pid}')
if topLogFile is not None:
topProcess.stop()
reCoreJar = re.compile('lucene-core-[0-9]+\\.[0-9]+\\.[0-9]+(?:-SNAPSHOT)?\\.jar')
class RunAlgs:
def __init__(self, javaCommand, verifyScores, verifyCounts):
self.logCounter = 0
self.results = []
self.compiled = set()
self.javaCommand = javaCommand
self.verifyScores = verifyScores
self.verifyCounts = verifyCounts
print()
print('JAVA:\n%s' % os.popen('%s -version 2>&1' % javaCommand).read())
print()
if osName not in ('windows', 'cygwin'):
print('OS:\n%s' % os.popen('uname -a 2>&1').read())
else:
print('OS:\n%s' % sys.platform)
if not os.path.exists(constants.LOGS_DIR):
os.makedirs(constants.LOGS_DIR)
print()
print('LOGS:\n%s' % constants.LOGS_DIR)
def printEnv(self):
print()
print('JAVA:\n%s' % os.popen('%s -version 2>&1' % self.javaCommand).read())
print
if osName not in ('windows', 'cygwin'):
print('OS:\n%s' % os.popen('uname -a 2>&1').read())
else:
print('OS:\n%s' % sys.platform)
def makeIndex(self, id, index, printCharts=False, profilerCount=30, profilerStackSize=1):
# we accept a sequence of stack sizes and will re-aggregate JFR results at each
if type(profilerStackSize) is int:
profilerStackSize = (profilerStackSize,)
fullIndexPath = nameToIndexPath(index.getName())
if os.path.exists(fullIndexPath) and not index.doUpdate:
print(' %s: already exists' % fullIndexPath)
return fullIndexPath
elif index.doUpdate:
if not os.path.exists(fullIndexPath):
raise RuntimeError('index path does not exists: %s' % fullIndexPath)
print(' %s: now update' % fullIndexPath)
else:
print(' %s: now create' % fullIndexPath)
s = checkoutToBenchPath(index.checkout)
print(' cd %s' % s)
os.chdir(s)
try:
cmd = []
cmd += index.javaCommand.split()
w = lambda *xs : [cmd.append(str(x)) for x in xs]
w('-classpath', classPathToString(getClassPath(index.checkout)))
jfrOutput = f'{constants.LOGS_DIR}/bench-index-{id}-{index.getName()}.jfr'
# 77: always enable Java Flight Recorder profiling
w(f'-XX:StartFlightRecording=dumponexit=true,maxsize=250M,settings={constants.BENCH_BASE_DIR}/src/python/profiling.jfc' +
f',filename={jfrOutput}',
'-XX:+UnlockDiagnosticVMOptions',
'-XX:+DebugNonSafepoints')
w('perf.Indexer')
w('-dirImpl', index.directory)
w('-indexPath', fullIndexPath)
w('-analyzer', index.analyzer)
w('-lineDocsFile', index.lineDocSource)
w('-docCountLimit', index.numDocs)
w('-threadCount', index.numThreads)
if index.maxConcurrentMerges is not None:
w('-maxConcurrentMerges', index.maxConcurrentMerges)
if index.addDVFields:
w('-dvfields')
if index.useCMS:
w('-useCMS')
if index.vectorFile:
w('-vectorFile', index.vectorFile)
w('-vectorDimension', index.vectorDimension)
w('-vectorEncoding', index.vectorEncoding)
if index.optimize:
w('-forceMerge')
if index.verbose:
w('-verbose')
w('-ramBufferMB', index.ramBufferMB)
w('-maxBufferedDocs', index.maxBufferedDocs)
w('-postingsFormat', index.postingsFormat)
if index.doDeletions:
w('-deletions')
if index.printDPS:
w('-printDPS')
if index.waitForMerges:
w('-waitForMerges')
w('-mergePolicy', index.mergePolicy)
if index.doUpdate:
w('-update')