Repository navigation
Expand file tree
/
Copy pathnightlyBench.py
More file actions
2381 lines (2015 loc) · 98.4 KB
/
Copy pathnightlyBench.py
File metadata and controls
2381 lines (2015 loc) · 98.4 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 datetime
import glob
import json
import os
import pickle
import random
import re
import shutil
import smtplib
import subprocess
import sys
import tarfile
import time
import traceback
import urllib.request
# local imports:
import benchUtil
import blunders
import competition
import constants
import fillNightlyFixedIndexTime
import fillNightlyTotalIndexSizes
import ps_head
import runFacetsBenchmark
import runNightlyKnn
import runStoredFieldsBenchmark
import stats
from notation import KNOWN_CHANGES
"""
This script runs certain benchmarks, once per day, and generates graphs so we can see performance over time:
* Index all of wikipedia ~ 1 KB docs w/ 512 MB ram buffer
* Run NRT perf test on this index for 30 minutes (we only plot mean/stddev reopen time)
* Index all of wikipedia actual (~4 KB) docs w/ 512 MB ram buffer
* Index all of wikipedia ~ 1 KB docs, flushing by specific doc count to get 5 segs per level
* Run search test
"""
# TODO
# - need a tiny docs test? catch per-doc overhead regressions...
# - click on graph should go to details page
# - nrt
# - chart all reopen times by time...?
# - chart over-time mean/stddev reopen time
# - maybe multiple queries on one graph...?
DEBUG = "-debug" in sys.argv
# NOTE: invented for debugging massive horror-regression 1/29/2026! due to CPU governor changing, combined with too old BIOS
# that that different governor failed to successfully interact with, causing fallback to absurdly-slow-but-for-sure-save CPU clocks
# see https://github.com/apache/lucene/issues/15662
REUSE_NIGHTLY_INDICES = False
REUSE_NIGHTLY_TIMESTAMP_DIR = "/l/logs.nightly/2026.02.10.07.46.04"
# NOTE: also invented for massive horror-regression 1/29/2026
ONLY_TASKS = False
JFR_STACK_SIZES = (1, 2, 4, 8, 12)
if DEBUG:
NIGHTLY_DIR = "trunk"
constants.GRADLE_EXE = f"{constants.BASE_DIR}/{NIGHTLY_DIR}/gradlew"
else:
NIGHTLY_DIR = "trunk.nightly"
DIR_IMPL = "MMapDirectory"
# Make sure we exercise Lucene's intra-query concurrency code paths:
SEARCH_CONCURRENCY = 8
INDEXING_RAM_BUFFER_MB = 2048
# "randomly" pick 5 queries for each category, but see validate_nightly_task_count where we
# enforce no more than this number of tasks in each category so that adding a new category
# of tasks will not cause other categories to pick different tasks
COUNTS_PER_CAT = 5
TASK_REPEAT_COUNT = 50
# MED_WIKI_BYTES_PER_DOC = 950.21921304868431
# BIG_WIKI_BYTES_PER_DOC = 4183.3843150398807
NRT_DOCS_PER_SECOND = 1103 # = 1 MB / avg med wiki doc size
NRT_RUN_TIME = 30 * 60
NRT_SEARCH_THREADS = 4
NRT_INDEX_THREADS = 1
NRT_REOPENS_PER_SEC = 1
JVM_COUNT = 20
if DEBUG:
NRT_RUN_TIME //= 90
JVM_COUNT = 3
reBytesIndexed = re.compile("^Indexer: net bytes indexed (.*)$", re.MULTILINE) # noqa: RUF039
reIndexingTime = re.compile(r"^Indexer: finished \((.*) msec\)", re.MULTILINE)
reSVNRev = re.compile(r"revision (.*?)\.")
reIndexAtClose = re.compile("Indexer: at close: (.*?)$", re.MULTILINE) # noqa: RUF039
reGitHubPROpen = re.compile(r"\s([0-9,]+) Open")
reGitHubPRClosed = re.compile(r"\s([0-9,]+) Closed")
# luceneutil#205: we accumulate the raw CSV values for every chart here, and write JSON in the end:
all_graph_data = {}
REAL = True
def get_cpu_info():
"""Detect CPU model and core/thread counts from the current machine via lscpu."""
try:
output = subprocess.check_output(["lscpu"], text=True)
model_name = ""
sockets = 1
cores_per_socket = 1
threads_per_core = 1
for line in output.splitlines():
if line.startswith("Model name:"):
model_name = line.split(":", 1)[1].strip()
elif line.startswith("Socket(s):"):
sockets = int(line.split(":", 1)[1].strip())
elif line.startswith("Core(s) per socket:"):
cores_per_socket = int(line.split(":", 1)[1].strip())
elif line.startswith("Thread(s) per core:"):
threads_per_core = int(line.split(":", 1)[1].strip())
total_cores = sockets * cores_per_socket * threads_per_core
return "%s (total %d cores = %d socket(s) * %d cores/socket * %d threads/core)" % (model_name, total_cores, sockets, cores_per_socket, threads_per_core)
except (OSError, ValueError) as e:
return "unknown CPU (error: %s)" % e
def get_disk_info(path=None):
"""Detect the physical disk backing the given path (e.g. constants.INDEX_DIR_BASE) via lsblk."""
try:
if path is None or not os.path.exists(path):
return get_all_disks_info()
source = subprocess.check_output(["df", "--output=source", path], text=True).strip().splitlines()[-1].strip()
if not source.startswith("/dev/"):
return source
output = subprocess.check_output(["lsblk", "-lsno", "NAME,TYPE,SIZE,MODEL", source], text=True).strip()
disks = []
for line in output.splitlines():
parts = line.split(None, 3)
if len(parts) >= 3 and parts[1] == "disk":
name = parts[0]
size = parts[2]
model = parts[3].strip() if len(parts) > 3 else ""
disks.append(f"{size} {model}" if model else f"{size} {name}")
if disks:
return "; ".join(disks)
return "unknown disk"
except (OSError, ValueError, subprocess.CalledProcessError) as e:
return "unknown disk (error: %s)" % e
def get_all_disks_info():
"""List all storage devices on the machine via lsblk."""
output = subprocess.check_output(
["lsblk", "-dno", "NAME,SIZE,MODEL"],
text=True,
).strip()
if not output:
return "unknown disk"
disks = []
for line in output.splitlines():
parts = line.split(None, 2)
name = parts[0] if len(parts) > 0 else ""
size = parts[1] if len(parts) > 1 else ""
model = parts[2].strip() if len(parts) > 2 else ""
if model:
disks.append(f"{size} {model}")
else:
disks.append(f"{size} {name}")
return "; ".join(disks)
def now():
return datetime.datetime.now()
def toSeconds(td):
return td.days * 86400 + td.seconds + td.microseconds / 1000000.0
def message(s):
print("[%s] %s" % (now(), s))
def runCommand(command):
if REAL:
message("RUN: %s" % command)
t0 = time.time()
if os.system(command):
message(" FAILED")
raise RuntimeError("command failed: %s" % command)
message(" took %.1f sec" % (time.time() - t0))
else:
message("WOULD RUN: %s" % command)
def extract_indexing_stats_from_log(log_file_name):
s = open(log_file_name).read()
bytesIndexed = int(reBytesIndexed.search(s).group(1))
m = reIndexAtClose.search(s)
if m is not None:
indexAtClose = m.group(1)
else:
# we have no index when we don't -waitForCommit
indexAtClose = None
indexTimeSec = int(reIndexingTime.search(s).group(1)) / 1000.0
return bytesIndexed, indexAtClose, indexTimeSec
def buildIndex(r, runLogDir, desc, index, logFile):
message("build %s" % desc)
# t0 = now()
indexPath = benchUtil.nameToIndexPath(index.getName())
if os.path.exists(indexPath):
if not REUSE_NIGHTLY_INDICES:
print(f'NOTE: removing old index "{desc}" at {indexPath}')
shutil.rmtree(indexPath)
else:
print(f'NOTE: REUSE_NIGHTLY_INDICES=True; reusing old index "{desc}" at {indexPath}')
# TODO: we should also sniff it a bit? confirm it's viable / matches doc count?
oldLogFileName = f"{REUSE_NIGHTLY_TIMESTAMP_DIR}/{logFile}"
if not os.path.exists(oldLogFileName):
raise RuntimeError(f'tried to reuse index "{desc}" at {indexPath} but log file {oldLogFileName} under {REUSE_NIGHTLY_TIMESTAMP_DIR=} does not exist?')
bytesIndexed, indexAtClose, indexTimeSec = extract_indexing_stats_from_log(oldLogFileName)
profilerResults = None
jfrFile = None
return indexPath, indexTimeSec, bytesIndexed, indexAtClose, profilerResults, jfrFile
# clean up after any failed runs first:
for tool in ("vmstat", "top"):
logFileName = f"{constants.LOGS_DIR}/nightly.{tool}.log"
if os.path.exists(logFileName):
print(f"remove pre-existing log file {logFileName}")
os.remove(logFileName)
# aggregate at multiple stack depths so we can see patterns like "new BytesRef() is costly regardless of context", for example:
indexPath, fullLogFile, profilerResults, jfrFile = r.makeIndex("nightly", index, profilerCount=50, profilerStackSize=JFR_STACK_SIZES, useLogSubDir=False, desc=desc)
# indexTime = (now()-t0)
newLogFileName = "%s/%s" % (runLogDir, logFile)
if REAL:
print("move log to %s" % newLogFileName)
shutil.move(fullLogFile, newLogFileName)
newVmstatLogFileName = f"{runLogDir}/{logFile.replace('.log', '.vmstat.log')}"
if REAL:
print("move vmstat log to %s" % newVmstatLogFileName)
shutil.move(f"{constants.LOGS_DIR}/nightly.vmstat.log", newVmstatLogFileName)
newTopLogFileName = f"{runLogDir}/{logFile.replace('.log', '.top.log')}"
if REAL:
print("move top log to %s" % newTopLogFileName)
shutil.move(f"{constants.LOGS_DIR}/nightly.top.log", newTopLogFileName)
bytesIndexed, indexAtClose, indexTimeSec = extract_indexing_stats_from_log(newLogFileName)
message(" took %.1f sec" % indexTimeSec)
fail_if_java_exceptions(f"buildIndex:{desc}", newLogFileName)
if "(fast)" in desc:
# don't run checkIndex: we rollback in the end
pass
else:
# checkIndex
checkLogFileName = "%s/checkIndex.%s" % (runLogDir, logFile)
checkIndex(r, indexPath, checkLogFileName)
return indexPath, indexTimeSec, bytesIndexed, indexAtClose, profilerResults, jfrFile
def checkIndex(r, indexPath, checkLogFileName):
message("run CheckIndex")
cmd = '%s -classpath "%s" -ea org.apache.lucene.index.CheckIndex -threadCount 16 -level 2 "%s" > %s 2>&1' % (
constants.JAVA_COMMAND,
benchUtil.classPathToString(benchUtil.getClassPath(NIGHTLY_DIR)),
indexPath + "/index",
checkLogFileName,
)
runCommand(cmd)
fail_if_java_exceptions("checkIndex:" + indexPath, checkLogFileName)
if open(checkLogFileName, encoding="utf-8").read().find("No problems were detected with this index") == -1:
raise RuntimeError("CheckIndex failed")
# Pattern matches common Java exception formats
EXCEPTION_PATTERN = re.compile(
r"(?:Exception|Error|Throwable)(?::|$)|"
r"^\s+at\s+[\w.$]+\([\w.]+:\d+\)|"
r"^\s+\.\.\.\s+\d+\s+more|"
r"Caused by:"
)
def fail_if_java_exceptions(desc, log_file):
with open(log_file) as f:
for line_num, line in enumerate(f, 1):
# MergeAbortedException is normal at the end of indexing when we rollback:
if EXCEPTION_PATTERN.search(line) and "org.apache.lucene.index.MergePolicy$MergeAbortedException" not in line:
raise RuntimeError(f'{desc}: java exceptions found in log file "{log_file}": line {line_num}: {line.rstrip()}')
reNRTReopenTime = re.compile("^Reopen: +([0-9.]+) msec$", re.MULTILINE) # noqa: RUF039
def runNRTTest(r, indexPath, runLogDir):
open("body10.tasks", "w").write("Term: body:10\n")
cmd = '%s -classpath "%s" perf.NRTPerfTest %s "%s" multi "%s" 17 %s %s %s %s %s update 5 no 0.0 body10.tasks' % (
constants.JAVA_COMMAND,
benchUtil.classPathToString(benchUtil.getClassPath(NIGHTLY_DIR)),
DIR_IMPL,
indexPath + "/index",
constants.NIGHTLY_MEDIUM_LINE_FILE,
NRT_DOCS_PER_SECOND,
NRT_RUN_TIME,
NRT_SEARCH_THREADS,
NRT_INDEX_THREADS,
NRT_REOPENS_PER_SEC,
)
logFile = "%s/nrt.log" % runLogDir
cmd += "> %s 2>&1" % logFile
runCommand(cmd)
fail_if_java_exceptions("runNRTTest", logFile)
times = []
for s in reNRTReopenTime.findall(open(logFile, encoding="utf-8").read()):
times.append(float(s))
# Discard first 10 (JVM warmup)
times = times[10:]
# Discard worst 2%
times.sort()
numDrop = len(times) // 50
if numDrop > 0:
message("drop: %s" % " ".join(["%.1f" % x for x in times[-numDrop:]]))
times = times[:-numDrop]
message("times: %s" % " ".join(["%.1f" % x for x in times]))
min, max, mean, stdDev = stats.getStats(times) # noqa: RUF059
message("NRT reopen time (msec) mean=%.4f stdDev=%.4f" % (mean, stdDev))
checkIndex(r, indexPath, "%s/checkIndex.nrt.log" % runLogDir)
return mean, stdDev
def validate_nightly_task_count(tasks_file, max_count):
"""We don't want tasks to randomly shift in the nightly benchy when we add a new category
of tasks, as we did/saw for count(*) tasks. so we enforce here that there are NO MORE
than N tasks in each category in the nightly tasks file.
"""
re_cat_and_task = re.compile("^([^:]+): (.*?)(?:#.*)?$") # noqa: RUF039
by_cat = {}
with open(tasks_file, encoding="utf-8") as f:
for line in f.readlines():
line = line.strip()
if len(line) > 0 and line[0] != "#":
# not a blank line nor comment line. it's real!
m = re_cat_and_task.match(line)
cat, task = m.groups()
if cat not in by_cat:
by_cat[cat] = set()
by_cat[cat].add(task)
for cat, tasks in by_cat.items():
if len(tasks) > max_count:
tasks_str = "\n ".join(tasks)
raise RuntimeError(f"nightly tasks file {tasks_file} must have at most {max_count} tasks in each category, but saw {len(tasks)}:\n {tasks_str}")
def run_print_log(cmd, desc, logDir, logFileName, do_print=True):
p = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=True)
s = p.stdout.strip()
fullLogFileName = f"{logDir}/{logFileName}"
with open(fullLogFileName, "w") as f: # noqa: FURB103
f.write(s)
if do_print:
if "\n" in s:
# multiple lines, so we force newline before first line
insert = "\n"
else:
# inline single line
insert = " "
print(f"\n\n{desc} (see also {fullLogFileName}): {cmd=}{insert}{s}")
return s
def run():
openPRCount, closedPRCount = countGitHubPullRequests()
MEDIUM_INDEX_NUM_DOCS = constants.NIGHTLY_MEDIUM_INDEX_NUM_DOCS
BIG_INDEX_NUM_DOCS = constants.NIGHTLY_BIG_INDEX_NUM_DOCS
if DEBUG:
# Must re-direct all logs/results/reports so we don't overwrite the "production" run's logs:
constants.LOGS_DIR = "/l/trunk/lucene/benchmark"
constants.NIGHTLY_LOG_DIR = f"{constants.BASE_DIR}/logs.debug"
constants.NIGHTLY_REPORTS_DIR = f"{constants.BASE_DIR}/reports.debug"
MEDIUM_INDEX_NUM_DOCS //= 100
BIG_INDEX_NUM_DOCS //= 100
DO_RESET = "-reset" in sys.argv
if DO_RESET:
print("will regold results files (command line specified)")
# TODO: remove this mechanism? best if we must commit a message to Lucene recording this instead?
regold_marker_file = f"{constants.BENCH_BASE_DIR}/regold_next_run"
if os.path.exists(regold_marker_file):
DO_RESET = True
os.remove(regold_marker_file)
print(f"saw regold marker file {regold_marker_file}; will regold results files")
validate_nightly_task_count(f"{constants.BENCH_BASE_DIR}/tasks/wikinightly.tasks", COUNTS_PER_CAT)
if not DEBUG:
# TODO: understand why the attempted removal in Competition.benchmark did not actually run for nightly bench!
for fileName in glob.glob(f"{constants.LOGS_DIR}/bench-search-*.jfr"):
print("Removing old JFR %s..." % fileName)
os.remove(fileName)
# gather other telemetry?
# make sure kernel module k10temp comes back on reboot
# should we tinker with preempt on boot?
# biolatency
# htop, btop
# turbostat
# cpupower (service and command-line tool?) frequency-info
# cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq
# cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
# grep MHz /proc/cpuinfo
# rdmsr
# lspci -vvv to
# dmesg
# turbostat
# /etc/default/cpupower
print()
print()
print()
print()
message("start")
id = "nightly"
if not REAL:
start = datetime.datetime(year=2011, month=5, day=19, hour=23, minute=00, second=0o1)
else:
start = now()
timeStamp = "%04d.%02d.%02d.%02d.%02d.%02d" % (start.year, start.month, start.day, start.hour, start.minute, start.second)
runLogDir = "%s/%s" % (constants.NIGHTLY_LOG_DIR, timeStamp)
if REAL:
os.makedirs(runLogDir)
message("log dir %s" % runLogDir)
os.chdir("%s/%s" % (constants.BASE_DIR, NIGHTLY_DIR))
javaVersion = run_print_log("%s -version 2>&1" % constants.JAVA_COMMAND, "Java version", runLogDir, "java_version.txt")
print("%s" % javaVersion)
javaFullVersion = run_print_log("%s -fullversion 2>&1" % constants.JAVA_COMMAND, "Java full version", runLogDir, "java_full_version.txt")
run_print_log(f"{constants.JAVA_COMMAND} -XX:+PrintFlagsFinal -version", "Java version & all flags", runLogDir, "java_final_flags.txt")
kernel_version = run_print_log("uname -a 2>&1", "Linux kernel version", runLogDir, "uname.txt")
# from 01/29/2026 pains (trust but verify!):
cpupower = run_print_log("cpupower frequency-info", "CPU governor/scaling/frequency", runLogDir, "cpu_frequency_info.txt")
lscpu = run_print_log("lscpu", "CPU specifics", runLogDir, "lscpu.txt")
run_print_log("cat /proc/cpuinfo", "More CPU specifics", runLogDir, "proc_cpuinfo.txt", do_print=False)
proc_version = run_print_log("cat /proc/version", "Full Linux version", runLogDir, "proc_version.txt")
proc_cmdline = run_print_log("cat /proc/cmdline", "Kernel boot command-line", runLogDir, "proc_cmdline.txt")
lsmod = run_print_log("lsmod", "Loaded kernel modules", runLogDir, "lsmod.txt")
preempt = run_print_log("sudo cat /sys/kernel/debug/sched/preempt", "Preempt mode", runLogDir, "preempt.txt")
dmesg = run_print_log("sudo dmesg", "Kernel console log", runLogDir, "dmesg.txt", do_print=False)
run_print_log("lsb_release -a", "Linux standard base version", runLogDir, "lsb.txt")
packages = run_print_log("pacman -Q", "All installed packages&versions", runLogDir, "pacman.txt")
if not REAL:
os.chdir("%s/%s" % (constants.BASE_DIR, NIGHTLY_DIR))
svnRev = "1102160"
luceneUtilRev = "2270c7a8b3ac+ tip"
print("SVN rev is %s" % svnRev)
print("luceneutil rev is %s" % luceneUtilRev)
luceneRev = os.popen("git rev-parse HEAD").read().strip()
else:
# nightly_strict.cmd has already git pull'd luceneutil & lucene
os.chdir(constants.BENCH_BASE_DIR)
luceneUtilRev = os.popen("git rev-parse HEAD").read().strip()
print(f"luceneutil rev is {luceneUtilRev}")
os.chdir("%s/%s" % (constants.BASE_DIR, NIGHTLY_DIR))
luceneRev = os.popen("git rev-parse HEAD").read().strip()
print(f"LUCENE rev is {luceneRev}")
lastRevs = findLastSuccessfulGitHashes()
if lastRevs is not None:
lastLuceneRev, lastLuceneUtilRev, lastLogFile = lastRevs
print(f"last successful Lucene rev {lastLuceneRev}, luceneutil rev {lastLuceneUtilRev}")
# parse git log to see if there were any commits requesting regold
command = ["git", "log", f"{lastLuceneRev}^..{luceneRev}"]
print(f"run {command}")
result = subprocess.run(command, check=True, capture_output=True)
regold_string = "// nightly-benchmarks-results-changed //"
if regold_string in result.stdout.decode("utf-8"):
print(f'Saw commit with "{regold_string}" comment from {" ".join(command)}; will regold results files')
DO_RESET = True
else:
print("No commit message asking for regold of results files")
os.chdir("%s/%s" % (constants.BASE_DIR, NIGHTLY_DIR))
runCommand("%s clean -xfd" % constants.GIT_EXE)
if not DEBUG and not DO_RESET:
print("will NOT regold results files but rather compare to last good result files")
print("Java command-line: %s" % constants.JAVA_COMMAND)
try:
s = open("/sys/kernel/mm/transparent_hugepage/enabled").read()
except:
print("Unable to read /sys/kernel/mm/transparent_hugepage/enabled")
else:
print("transparent_hugepages: %s" % s)
runCommand("%s --stacktrace clean > %s/clean-lucene.log 2>&1" % (constants.GRADLE_EXE, runLogDir))
runCommand("%s jar > %s/jar-lucene.log 2>&1" % (constants.GRADLE_EXE, runLogDir))
verifyScores = True
# When intra-query concurrency is used we will not consistently return the same
# estimated hit counts (I think?)
verifyCounts = SEARCH_CONCURRENCY == 1
r = benchUtil.RunAlgs(constants.JAVA_COMMAND, verifyScores, verifyCounts)
comp = competition.Competition(
taskRepeatCount=TASK_REPEAT_COUNT,
taskCountPerCat=COUNTS_PER_CAT,
verifyCounts=False, # only verify top hits, not counts
jvmCount=20,
)
mediumSource = competition.Data("wikimedium", constants.NIGHTLY_MEDIUM_LINE_FILE, MEDIUM_INDEX_NUM_DOCS, constants.WIKI_MEDIUM_TASKS_FILE)
fastIndexMedium = comp.newIndex(
NIGHTLY_DIR,
mediumSource,
analyzer="StandardAnalyzerNoStopWords",
postingsFormat="Lucene104",
numThreads=constants.INDEX_NUM_THREADS,
directory=DIR_IMPL,
idFieldPostingsFormat="Lucene104",
ramBufferMB=INDEXING_RAM_BUFFER_MB,
waitForMerges=False,
waitForCommit=False,
grouping=False,
verbose=False,
mergePolicy="TieredMergePolicy",
useCMS=True,
)
fastIndexMediumVectors = comp.newIndex(
NIGHTLY_DIR,
mediumSource,
analyzer="StandardAnalyzerNoStopWords",
postingsFormat="Lucene104",
numThreads=constants.INDEX_NUM_THREADS,
directory=DIR_IMPL,
idFieldPostingsFormat="Lucene104",
ramBufferMB=INDEXING_RAM_BUFFER_MB,
waitForMerges=False,
waitForCommit=False,
grouping=False,
verbose=True, # TODO: turn off again once we validate if there is HNSW concurrency bug https://github.com/mikemccand/luceneutil/pull/507#discussion_r3045850830
mergePolicy="TieredMergePolicy",
useCMS=True,
vectorFile=constants.VECTORS_DOCS_FILE,
vectorDimension=constants.VECTORS_DIMENSIONS,
vectorEncoding=constants.VECTORS_TYPE,
hnswThreadsPerMerge=constants.HNSW_THREADS_PER_MERGE,
hnswThreadPoolCount=constants.HNSW_THREAD_POOL_COUNT,
)
fastIndexMediumVectorsQuantized = comp.newIndex(
NIGHTLY_DIR,
mediumSource,
analyzer="StandardAnalyzerNoStopWords",
postingsFormat="Lucene104",
numThreads=constants.INDEX_NUM_THREADS,
directory=DIR_IMPL,
idFieldPostingsFormat="Lucene104",
ramBufferMB=INDEXING_RAM_BUFFER_MB,
waitForMerges=False,
waitForCommit=False,
grouping=False,
verbose=False,
mergePolicy="TieredMergePolicy",
useCMS=True,
vectorFile=constants.VECTORS_DOCS_FILE,
vectorDimension=constants.VECTORS_DIMENSIONS,
vectorEncoding=constants.VECTORS_TYPE,
quantizeKNNGraph=True,
hnswThreadsPerMerge=constants.HNSW_THREADS_PER_MERGE,
hnswThreadPoolCount=constants.HNSW_THREAD_POOL_COUNT,
)
nrtIndexMedium = comp.newIndex(
NIGHTLY_DIR,
mediumSource,
analyzer="StandardAnalyzerNoStopWords",
postingsFormat="Lucene104",
numThreads=constants.INDEX_NUM_THREADS,
directory=DIR_IMPL,
idFieldPostingsFormat="Lucene104",
ramBufferMB=INDEXING_RAM_BUFFER_MB,
waitForMerges=True,
waitForCommit=True,
grouping=False,
verbose=False,
mergePolicy="TieredMergePolicy",
useCMS=True,
addDVFields=True,
)
bigSource = competition.Data("wikibig", constants.NIGHTLY_BIG_LINE_FILE, BIG_INDEX_NUM_DOCS, constants.WIKI_MEDIUM_TASKS_FILE)
fastIndexBig = comp.newIndex(
NIGHTLY_DIR,
bigSource,
analyzer="StandardAnalyzerNoStopWords",
postingsFormat="Lucene104",
numThreads=constants.INDEX_NUM_THREADS,
directory=DIR_IMPL,
idFieldPostingsFormat="Lucene104",
ramBufferMB=INDEXING_RAM_BUFFER_MB,
waitForMerges=False,
waitForCommit=False,
grouping=False,
verbose=False,
mergePolicy="TieredMergePolicy",
useCMS=True,
)
# Must use only 1 thread so we get same index structure, always:
index = comp.newIndex(
NIGHTLY_DIR,
mediumSource,
analyzer="StandardAnalyzerNoStopWords",
postingsFormat="Lucene104",
numThreads=1,
useCMS=False,
directory=DIR_IMPL,
idFieldPostingsFormat="Lucene104",
mergePolicy="LogDocMergePolicy",
facets=(
("taxonomy:Date", "Date"),
("taxonomy:Month", "Month"),
("taxonomy:DayOfYear", "DayOfYear"),
("sortedset:Month", "Month"),
("sortedset:DayOfYear", "DayOfYear"),
("sortedset:Date", "Date"),
("taxonomy:RandomLabel", "RandomLabel"),
("sortedset:RandomLabel", "RandomLabel"),
),
addDVFields=True,
addDVSkippers=True,
vectorFile=constants.VECTORS_DOCS_FILE,
vectorDimension=constants.VECTORS_DIMENSIONS,
vectorEncoding=constants.VECTORS_TYPE,
hnswThreadsPerMerge=constants.HNSW_THREADS_PER_MERGE,
hnswThreadPoolCount=constants.HNSW_THREAD_POOL_COUNT,
)
# this index is gigantic -- if a turd is leftover from a prior failed run, nuke it now!!
if not REUSE_NIGHTLY_INDICES:
index_path = benchUtil.nameToIndexPath(index.getName())
if os.path.exists(index_path):
print(f"NOTE: now delete old leftover ginormous index {index_path}")
shutil.rmtree(index_path)
c = comp.competitor(
id,
NIGHTLY_DIR,
index=index,
# vectorDict=(constants.VECTORS_WORD_TOK_FILE, constants.VECTORS_WORD_VEC_FILE, constants.VECTORS_DIMENSIONS),
vectorFileName=constants.VECTORS_QUERY_FILE,
vectorDimension=constants.VECTORS_DIMENSIONS,
directory=DIR_IMPL,
commitPoint="multi",
numConcurrentQueries=1,
searchConcurrency=SEARCH_CONCURRENCY,
)
# c = benchUtil.Competitor(id, 'trunk.nightly', index, DIR_IMPL, 'StandardAnalyzerNoStopWords', 'multi', constants.WIKI_MEDIUM_TASKS_FILE)
if REAL:
r.compile(c)
if not ONLY_TASKS and not DEBUG and not DO_RESET:
# stored fields benchy
os.chdir(constants.BENCH_BASE_DIR)
try:
message("now run stored fields benchmark")
if not REAL or DEBUG:
doc_limit = 100000
else:
# do all docs in the file
doc_limit = -1
runStoredFieldsBenchmark.run_benchmark(
f"{constants.BASE_DIR}/{NIGHTLY_DIR}", constants.GEONAMES_LINE_FILE_DOCS, f"{constants.INDEX_DIR_BASE}/geonames-stored-fields-nightly", runLogDir, doc_limit
)
message("done run stored fields benchmark")
finally:
os.chdir("%s/%s" % (constants.BASE_DIR, NIGHTLY_DIR))
# high cardinality facets
os.chdir(constants.BENCH_BASE_DIR)
try:
message("now run NAD facets benchmark")
if not REAL or DEBUG:
doc_limit = 100000
num_iters = 2
else:
doc_limit = -1
num_iters = 30
index_dir_name = f"{constants.INDEX_DIR_BASE}/nad-facets-nightly"
runFacetsBenchmark.run_benchmark(f"{constants.BASE_DIR}/{NIGHTLY_DIR}", index_dir_name, f"{constants.BASE_DIR}/data", runLogDir, doc_limit, num_iters)
message("done run NAD facets benchmark")
shutil.rmtree(index_dir_name)
finally:
os.chdir("%s/%s" % (constants.BASE_DIR, NIGHTLY_DIR))
# KNN
os.chdir(constants.BENCH_BASE_DIR)
try:
message("now run KNN benchmark")
runNightlyKnn.run(runLogDir)
message("now generate KNN nightly charts")
runNightlyKnn.write_graph()
except:
print("Nightly KNN benchy failed; ignoring:")
traceback.print_exc()
finally:
os.chdir("%s/%s" % (constants.BASE_DIR, NIGHTLY_DIR))
if not ONLY_TASKS:
# 1: test indexing speed: small (~ 1KB) sized docs, flush-by-ram
medIndexPath, medIndexTime, medBytesIndexed, atClose, profilerMediumIndex, profilerMediumJFR = buildIndex(r, runLogDir, "medium index (fast)", fastIndexMedium, "fastIndexMediumDocs.log")
message("medIndexAtClose %s" % atClose)
if REUSE_NIGHTLY_INDICES:
print(f'NOTE: REUSE_NIGHTLY_INDICES=True; keeping "medium index (fast)" at {medIndexPath}')
else:
shutil.rmtree(medIndexPath)
# 2: test indexing speed: small (~ 1KB) sized docs, flush-by-ram, with vectors
medVectorsIndexPath, medVectorsIndexTime, medVectorsBytesIndexed, atClose, profilerMediumVectorsIndex, profilerMediumVectorsJFR = buildIndex(
r, runLogDir, "medium vectors index (fast)", fastIndexMediumVectors, "fastIndexMediumDocsWithVectors.log"
)
message("medIndexVectorsAtClose %s" % atClose)
if REUSE_NIGHTLY_INDICES:
print(f'NOTE: REUSE_NIGHTLY_INDICES=True; keeping "medium vectors index (fast)" at {medVectorsIndexPath}')
else:
shutil.rmtree(medVectorsIndexPath)
# 2.5: test indexing speed: small (~ 1KB) sized docs, flush-by-ram, with vectors, quantized
# TODO: render profiler data for thias run too
medQuantizedVectorsIndexPath, medQuantizedVectorsIndexTime, medQuantizedVectorsBytesIndexed, atClose, profilerMediumQuantizedVectorsIndex, profilerMediumQuantizedVectorsJFR = buildIndex( # noqa: RUF059
r, runLogDir, "medium quantized vectors index (fast)", fastIndexMediumVectorsQuantized, "fastIndexMediumDocsWithVectorsQuantized.log"
)
message("medIndexVectorsAtClose %s" % atClose)
if REUSE_NIGHTLY_INDICES:
print(f'NOTE: REUSE_NIGHTLY_INDICES=True; keeping "medium quantized vectors index (fast)" at {medQuantizedVectorsIndexPath}')
else:
shutil.rmtree(medQuantizedVectorsIndexPath)
# 3: build index for NRT test
nrtIndexPath, nrtIndexTime, nrtBytesIndexed, atClose, profilerNRTIndex, profilerNRTJFR = buildIndex(r, runLogDir, "nrt medium index", nrtIndexMedium, "nrtIndexMediumDocs.log") # noqa: RUF059
message("nrtMedIndexAtClose %s" % atClose)
nrtResults = runNRTTest(r, nrtIndexPath, runLogDir)
if REUSE_NIGHTLY_INDICES:
print(f'NOTE: REUSE_NIGHTLY_INDICES=True; keeping "nrt medium index" at {nrtIndexPath}')
else:
shutil.rmtree(nrtIndexPath)
# 4: test indexing speed: medium (~ 4KB) sized docs, flush-by-ram
bigIndexPath, bigIndexTime, bigBytesIndexed, atClose, profilerBigIndex, profilerBigJFR = buildIndex(r, runLogDir, "big index (fast)", fastIndexBig, "fastIndexBigDocs.log")
message("bigIndexAtClose %s" % atClose)
if REUSE_NIGHTLY_INDICES:
print(f'NOTE: REUSE_NIGHTLY_INDICES=True; keeping "big index (fast)" at {bigIndexPath}')
else:
shutil.rmtree(bigIndexPath)
# 5: test searching speed; first build index, flushed by doc count (so we get same index structure night to night)
# TODO: switch to concurrent yet deterministic indexer: https://markmail.org/thread/cp6jpjuowbhni6xc
indexPathNow, fixedIndexTime, fixedIndexBytesIndexed, atClose, profilerSearchIndex, profilerSearchJFR = buildIndex(r, runLogDir, "search index (fixed segments)", index, "fixedIndex.log")
message("fixedIndexAtClose %s" % atClose)
fixedIndexAtClose = atClose
indexPathPrev = "%s/trunk.nightly.index.prev" % constants.INDEX_DIR_BASE
indexCurPath = benchUtil.nameToIndexPath(index.getName())
if os.path.exists(indexPathPrev) and os.path.exists(indexCurPath):
segCountPrev = benchUtil.getSegmentCount(indexPathPrev)
segCountNow = benchUtil.getSegmentCount(indexCurPath)
if segCountNow != segCountPrev:
raise RuntimeError("different index segment count prev=%s now=%s" % (segCountPrev, segCountNow))
# print("WARNING: different index segment count prev=%s now=%s" % (segCountPrev, segCountNow))
# Search
rand = random.Random(714)
staticSeed = rand.randint(-10000000, 1000000)
# staticSeed = -1492352
message("search")
t0 = now()
coldRun = False
comp = c
comp.tasksFile = f"{constants.BENCH_BASE_DIR}/tasks/wikinightly.tasks"
comp.printHeap = True
if REAL:
vmstatLogFile = f"{runLogDir}/search-tasks.vmstat.log"
topLogFile = f"{runLogDir}/search-tasks.top.log"
vmstatCmd = f"{benchUtil.VMSTAT_PATH} --active --wide --timestamp --unit M 1 > {vmstatLogFile} 2>/dev/null &"
print(f"run vmstat: {vmstatCmd}")
vmstatProcess = subprocess.Popen(vmstatCmd, shell=True, preexec_fn=os.setsid)
topProcess = ps_head.PSTopN(10, topLogFile)
print(f"run {topProcess.cmd} to {topLogFile}")
resultsNow = []
for iter in range(JVM_COUNT):
seed = rand.randint(-10000000, 1000000)
resultsNow.append(r.runSimpleSearchBench(iter, id, comp, coldRun, seed, staticSeed, filter=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", benchUtil.get_username(), "vmstat"])
if vmstatProcess.poll() is None:
raise RuntimeError("failed to kill vmstat child process? pid={vmstatProcess.pid}")
topProcess.stop()
else:
resultsNow = ["%s/%s/modules/benchmark/%s.%s.x.%d" % (constants.BASE_DIR, NIGHTLY_DIR, id, comp.name, iter) for iter in range(JVM_COUNT)]
message("done search (%s)" % (now() - t0))
resultsPrev = []
searchResults = searchHeap = None
for fname in resultsNow:
prevFName = fname + ".prev"
if os.path.exists(prevFName):
resultsPrev.append(prevFName)
if len(resultsPrev) == 0:
# sidestep exception when we can't find any previous results because DEBUG
print("WARNING: no prior results; switching comparison to A/A")
resultsPrev = resultsNow
# save all results files to benchy log dir (timestamped global benchy logs if nightly benchy) so
# they are visible even if there were hit differences that fail the benchy
for fname in resultsNow:
shutil.copy(fname, runLogDir)
if os.path.exists(fname + ".stdout"):
shutil.copy(fname + ".stdout", runLogDir)
output = []
results, cmpDiffs, searchHeaps = r.simpleReport(resultsPrev, resultsNow, False, True, "prev", "now", writer=output.append)
# generate vmstat pretties
print("generate vmstat pretties")
timestampLogDir = f"{constants.NIGHTLY_REPORTS_DIR}/{timeStamp}"
os.mkdir(timestampLogDir)
os.chdir(timestampLogDir)
with open("index.html", "w") as indexOut:
indexOut.write("<h2>vmstat charts for indexing tasks</h2>\n")
for vmstatLogFileName in glob.glob(f"{runLogDir}/*.vmstat.log"):
prefix = os.path.split(vmstatLogFileName)[1][:-11]
indexOut.write(f"<a href={prefix}>{prefix}</a><br>\n")
# a new sub-directory per run since each vmstat generates a bunch of pretties
subDirName = f"{timestampLogDir}/{prefix}"
os.mkdir(subDirName)
print(f" {subDirName}")
# TODO: optimize to single shared copy!
shutil.copy("/usr/share/gnuplot/6.0/js/gnuplot_svg.js", subDirName)
shutil.copy(f"{constants.BENCH_BASE_DIR}/src/vmstat/index.html.template", f"{subDirName}/index.html")
subprocess.check_call(f"gnuplot -c {constants.BENCH_BASE_DIR}/src/vmstat/vmstat.gpi {vmstatLogFileName} {prefix}", shell=True)
with open("%s/%s.html" % (constants.NIGHTLY_REPORTS_DIR, timeStamp), "w") as f:
timeStamp2 = "%s %02d/%02d/%04d" % (start.strftime("%a"), start.month, start.day, start.year)
w = f.write
w("<html>\n")
w("<h1>%s</h1>" % timeStamp2)
if DO_RESET:
w("<b>NOTE</b>: this run regolded the results gold files<br><br>")
if timeStamp > "2026-01-04":
# we only turned this on "recently"
w(f'\n[<a href="{timeStamp}/all.log">top-level log from this run</a>]<br>\n')
if lastRevs is not None:
w(f'\nLast successful run: <a href="{lastLogFile}">{lastLogFile[:-5]}</a><br>')
if lastLuceneRev != luceneRev:
w(f'\nLucene/Solr trunk rev {luceneRev} (<a href="https://github.com/apache/lucene/compare/{lastLuceneRev}...{luceneRev}">commits since last successful run</a>)<br>')
else:
w(f"\nLucene/Solr trunk rev {luceneRev} (no changes since last successful run)<br>")
if lastLuceneUtilRev != luceneUtilRev:
w(f'\nluceneutil revision {luceneUtilRev} (<a href="https://github.com/mikemccand/luceneutil/compare/{lastLuceneUtilRev}...{luceneUtilRev}">commits since last successful run</a>)<br>')
else:
w(f"\nluceneutil revision {luceneUtilRev} (no changes since last successful run)<br>")
w(f"\nuname -a: {kernel_version}<br>")
w(f"\n/proc/version: {proc_version}<br>")
w(f"\n/proc/cmdline: {proc_cmdline}<br>")
w(f"\ncpupower frequency-info:\n<br><pre>{htmlEscape(cpupower)}</pre><br>")
w(f"\nlscpu:\n<br><pre>{htmlEscape(lscpu)}</pre><br>")
w(f"\nPreempt mode: {preempt}<br>")
w("%s<br>" % javaVersion)
w("%s<br>" % javaFullVersion)
w("Java command-line: %s<br>" % htmlEscape(constants.JAVA_COMMAND))
w("Index: %s<br>" % fixedIndexAtClose)
w(f'See the <a href="{timeStamp}/index.html">perty vmstat charts</a>\n')
w("<br><br><b>Search perf vs day before</b>\n")
w("".join(output))
w("<br><br>")
w('<img src="%s.png"/>\n' % timeStamp)
w("Jump to profiler results:")
if benchUtil.USE_CPU_TIME_PROFILER:
s = "cputime (samples every N cpu ticks)"
else:
s = "async (samples every N msec)"
w("<br>")
w(f'<b>NOTE</b>: JFR profiler is {s}; see <a href="https://mostlynerdless.de/blog/2025/06/11/java-25s-new-cpu-time-profiler-1/">blog post</a> for cputime profiler (new as of Java 25) specifics')
w("<br>indexing 1KB\n<ul>")
for stackSize in JFR_STACK_SIZES:
w(f'<li>stackSize={stackSize}: <a href="#profiler_1kb_indexing_{stackSize}_cpu">cpu</a>, <a href="#profiler_1kb_indexing_{stackSize}_heap">heap</a>')
w("</ul>")
w("<br>indexing 1KB (with vectors)\n<ul>")
for stackSize in JFR_STACK_SIZES:
w(f'<li>stackSize={stackSize}: <a href="#profiler_1kb_indexing_vectors_{stackSize}_cpu">cpu</a>, <a href="#profiler_1kb_indexing_vectors_{stackSize}_heap">heap</a>')
w("</ul>")
w("<br>indexing 4KB\n<ul>")
for stackSize in JFR_STACK_SIZES:
w(f'<li>stackSize={stackSize}: <a href="#profiler_4kb_indexing_{stackSize}_cpu">cpu</a>, <a href="#profiler_4kb_indexing_{stackSize}_heap">heap</a>')
w("</ul>")
w("<br>indexing near-real-timeB\n<ul>")
for stackSize in JFR_STACK_SIZES:
w(f'<li>stackSize={stackSize}: <a href="#profiler_nrt_indexing_{stackSize}_cpu">cpu</a>, <a href="#profiler_nrt_indexing_{stackSize}_heap">heap</a>')
w("</ul>")
w("<br>deterministic (single threaded) indexing<ul>")
for stackSize in JFR_STACK_SIZES:
w(f'<li>stackSize={stackSize}: <a href="#profiler_deterministic_indexing_{stackSize}_cpu">cpu</a>, <a href="#profiler_deterministic_indexing_{stackSize}_heap">heap</a>')
w("</ul>")
w("<br>searching<ul>")