-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathvalkey_benchmark.py
More file actions
1621 lines (1443 loc) · 61.7 KB
/
Copy pathvalkey_benchmark.py
File metadata and controls
1621 lines (1443 loc) · 61.7 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
"""Client-side benchmark execution logic."""
import copy
import logging
import random
import shlex
import subprocess
import time
import csv
from contextlib import contextmanager
from pathlib import Path
from typing import Iterable, List, Optional
import valkey
from process_metrics import MetricsProcessor
from valkey_server import ServerLauncher, apply_config_to_servers
from profiler import PerformanceProfiler
from utils.git_utils import resolve_ref, get_commit_timestamp
from utils.cpu_utils import format_core_list, parse_core_range
from environment_metadata import collect_environment_metadata
# Constants
VALKEY_BENCHMARK = "src/valkey-benchmark"
DEFAULT_PORT = 6379
DEFAULT_TIMEOUT = 30
# Supported Valkey benchmark commands
READ_COMMANDS = ["GET", "MGET", "LRANGE", "SISMEMBER", "ZSCORE", "ZRANGE"]
WRITE_COMMANDS = [
"SET",
"MSET",
"INCR",
"LPUSH",
"RPUSH",
"LPOP",
"RPOP",
"SADD",
"HSET",
"ZADD",
"XADD",
"SPOP",
"ZPOPMIN",
]
# Map for read commands to populate equivalents
READ_POPULATE_MAP = {
"GET": "SET",
"MGET": "MSET",
"LRANGE": "LPUSH",
"SISMEMBER": "SADD",
"ZSCORE": "ZADD",
"ZRANGE": "ZADD",
}
# Compiled basic scenarios retain the basic metrics schema and shared seed.
ORIGIN_FIELD = "_origin"
ORIGIN_SIMPLE = "simple"
def deep_merge(base: dict, override: dict) -> dict:
"""Deep merge override into base, returning new dict."""
result = copy.deepcopy(base)
for key, value in override.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
class ClientRunner:
"""Run ``valkey-benchmark`` for a given commit and configuration."""
def __init__(
self,
commit_id: str,
config: dict,
cluster_mode: bool,
tls_mode: bool,
target_ip: str,
results_dir: Path,
valkey_path: str,
cores: Optional[str] = None,
io_threads: Optional[int] = None,
valkey_benchmark_path: Optional[str] = None,
benchmark_threads: Optional[int] = None,
runs: int = 1,
server_launcher: Optional[ServerLauncher] = None,
architecture: Optional[str] = None,
repository: Optional[str] = None,
config_name: Optional[str] = None,
module_commit: Optional[str] = None,
module_commit_timestamp: Optional[str] = None,
) -> None:
self.commit_id = commit_id
self.config = config
self.cluster_mode = cluster_mode
self.tls_mode = tls_mode
self.target_ip = target_ip
self.results_dir = results_dir
self.valkey_path = Path(valkey_path)
self.cores = cores
self.io_threads = io_threads
self.valkey_benchmark_path = valkey_benchmark_path or VALKEY_BENCHMARK
self.benchmark_threads = benchmark_threads
self.runs = runs
self.server_launcher = server_launcher
self.architecture = architecture
self.repository = repository
self.config_name = config_name
self.module_commit = module_commit
self.module_commit_timestamp = module_commit_timestamp
self.current_profiling_set = {"enabled": False}
self.current_config_set = {}
self.config_suffix = "default"
self.client_cpu_ranges = []
def _create_client(self, port: Optional[int] = None) -> valkey.Valkey:
"""Return a Valkey client configured for TLS or plain mode."""
if port is None:
port = self.config.get("port", DEFAULT_PORT)
logging.info(f"Connecting to {self.target_ip}:{port}")
kwargs = {
"host": self.target_ip,
"port": port,
"decode_responses": True,
"socket_timeout": 10,
"socket_connect_timeout": 10,
}
if self.tls_mode:
tls_cert_path = Path(self.valkey_path) / "tests" / "tls"
if not tls_cert_path.exists():
raise FileNotFoundError(
f"TLS certificates not found at {tls_cert_path}"
)
kwargs.update(
{
"ssl": True,
"ssl_certfile": str(tls_cert_path / "valkey.crt"),
"ssl_keyfile": str(tls_cert_path / "valkey.key"),
"ssl_ca_certs": str(tls_cert_path / "ca.crt"),
}
)
return valkey.Valkey(**kwargs)
@contextmanager
def _client_context(self):
"""Context manager for Valkey client connections."""
client = None
try:
client = self._create_client()
yield client
finally:
if client:
try:
client.close()
except Exception as e:
logging.warning(f"Error closing client connection: {e}")
def _run(
self,
command: Iterable[str],
cwd: Optional[Path] = None,
capture_output: bool = False,
text: bool = True,
timeout: Optional[int] = 300,
) -> Optional[subprocess.CompletedProcess]:
"""Execute a command with proper error handling and timeout."""
cmd_list = list(command)
cmd_str = shlex.join(cmd_list)
logging.info(f"Running: {cmd_str}")
try:
result = subprocess.run(
cmd_list,
shell=False,
cwd=cwd,
capture_output=capture_output,
text=text,
check=True,
timeout=timeout,
)
if result.stderr:
logging.warning(f"Command stderr: {result.stderr}")
return result if capture_output else None
except subprocess.TimeoutExpired as e:
logging.error(f"Command timed out after {timeout}s: {cmd_str}")
raise RuntimeError(f"Command timed out: {cmd_str}") from e
except subprocess.CalledProcessError as e:
logging.error(f"Command failed with exit code {e.returncode}: {cmd_str}")
if e.stderr:
logging.error(f"Command stderr: {e.stderr}")
raise RuntimeError(f"Command failed: {cmd_str}") from e
except Exception as e:
logging.error(f"Unexpected error while running: {cmd_str}")
raise RuntimeError(f"Unexpected error: {cmd_str}") from e
def wait_for_server_ready(self, timeout: int = DEFAULT_TIMEOUT) -> None:
"""Poll until the Valkey server responds to PING or timeout expires."""
logging.info(
"Waiting for Valkey server to be ready from the benchmark client..."
)
start = time.time()
last_error = None
while time.time() - start < timeout:
try:
with self._client_context() as client:
client.ping()
logging.info("Valkey server is ready.")
return
except Exception as e:
last_error = e
time.sleep(1)
logging.error(f"Valkey server did not become ready within {timeout} seconds.")
if last_error:
logging.error(f"Last connection error: {last_error}")
raise RuntimeError(f"Server failed to start in time. Last error: {last_error}")
def get_commit_time(self, commit_id: str) -> str:
"""Return timestamp for a commit."""
try:
sha = resolve_ref(commit_id, self.valkey_path)
return get_commit_timestamp(sha, self.valkey_path)
except Exception as e:
logging.exception(f"Failed to get commit time for {commit_id}: {e}")
raise
def _get_active_ports(self) -> List[int]:
"""Return ports based on actual cluster mode."""
if self.cluster_mode and "cluster_ports" in self.config:
return self.config["cluster_ports"]
return [self.config.get("port", 6379)]
def _should_add_cluster_flag(self, scenario: Optional[dict] = None) -> bool:
"""Return whether the valkey-benchmark command should include --cluster."""
if not self.cluster_mode:
return False
if scenario is None:
return True
return scenario.get("cluster_execution", "single") == "single"
def _flush_database(self) -> None:
"""Flush all data from the database before benchmark runs."""
logging.info(
"Flushing database before benchmark run (may take several minutes for large indexes)"
)
try:
ports = self._get_active_ports()
# Drop indexes first with extended timeout (large indexes take time)
try:
# Extended timeout for index operations
first_client = self._create_client(port=ports[0])
first_client.connection_pool.connection_kwargs["socket_timeout"] = 300
try:
indexes = first_client.execute_command("FT._LIST")
for idx in indexes:
try:
logging.info(f"Dropping index {idx}...")
first_client.execute_command("FT.DROPINDEX", idx)
logging.info(f"Dropped index {idx}")
except Exception as e:
logging.warning(f"Could not drop index {idx}: {e}")
finally:
first_client.close()
except Exception as e:
logging.warning(f"Could not list/drop indexes: {e}")
# Flush all nodes with extended timeout
for port in ports:
client = self._create_client(port=port)
client.connection_pool.connection_kwargs["socket_timeout"] = 300
try:
logging.info(f"Flushing database on port {port}...")
client.flushall(asynchronous=False)
logging.info(f"Flushed database on port {port}")
finally:
client.close()
except Exception as e:
logging.error(f"Failed to flush database: {e}")
raise RuntimeError(f"Database flush failed: {e}")
def _apply_config_set(self, config_set: dict) -> None:
"""Apply CONFIG SET commands to all server nodes after restart."""
apply_config_to_servers(
config_set,
self._get_active_ports(),
self.target_ip,
tls_mode=self.tls_mode,
valkey_dir=self.valkey_path,
)
def _populate_keyspace(
self,
workload_key: str,
write_workload: str,
requests: int,
keyspacelen: int,
data_size: int,
pipeline: int,
clients: int,
seed_val: int,
) -> None:
"""Run a sequential write workload to seed the keyspace."""
logging.info(f"Populating keyspace using {write_workload}")
populate_scenario = {
workload_key: write_workload,
"requests": requests,
"keyspacelen": keyspacelen,
"data_size": data_size,
"pipeline": pipeline,
"clients": clients,
"sequential": True,
}
bench_cmd = self._build_benchmark_command(
populate_scenario, tls=self.tls_mode, seed_val=seed_val
)
self._run(command=bench_cmd, cwd=self.valkey_path, timeout=None)
logging.info(f"Keyspace populated using {write_workload} with {requests} keys")
def run_benchmark_config(self) -> None:
"""Execute the configured scenarios and persist their metrics."""
commit_time = self.get_commit_time(self.commit_id)
(
profiler,
metrics_processor,
profiling_enabled,
) = self._setup_profiling_and_metrics(self.current_profiling_set, commit_time)
metric_json = []
for scenario_data in self._iterate_test_groups_scenarios():
result = self._run_single_scenario(
scenario_data["scenario"],
scenario_data["group_id"],
profiler,
metrics_processor,
scenario_data["config_set"],
scenario_data["config_suffix"],
scenario_data.get("group_description"),
)
if result:
if isinstance(result, list):
metric_json.extend(result)
else:
metric_json.append(result)
self._finalize_metrics(metrics_processor, metric_json, profiling_enabled)
def _get_effective_runs(self) -> int:
"""Return one run while profiling, otherwise the configured count."""
if self.current_profiling_set.get("enabled", False) and self.runs > 1:
logging.info("Profiling enabled: forcing runs=1 (profiling runs only once)")
return 1
return self.runs
def _iterate_test_groups_scenarios(self):
"""Yield scenarios in group/run/scenario order."""
effective_runs = self._get_effective_runs()
groups_to_run = self.config.get("groups_to_run")
scenario_filter = self.config.get("scenario_filter")
for test_group in self.config.get("test_groups", []):
group_id = test_group.get("group", "unknown")
group_description = test_group.get("description")
if groups_to_run and group_id not in groups_to_run:
logging.info(
f"Skipping group {group_id} (not in filter: {groups_to_run})"
)
continue
for run_num in range(effective_runs):
if effective_runs > 1:
logging.info(
f"=== Group {group_id}: {group_description or ''} "
f"(run {run_num + 1}/{effective_runs}) ==="
)
else:
logging.info(f"=== Group {group_id}: {group_description or ''} ===")
for scenario in test_group.get("scenarios", []):
# Cluster mode is scalarized only at execution time.
test_cmd = scenario.get("test")
if test_cmd in ("MSET", "MGET") and self.cluster_mode:
logging.warning(
f"Command {test_cmd} not supported in cluster mode, skipping."
)
continue
for expanded_scenario in self._expand_scenario_options(scenario):
if (
scenario_filter
and expanded_scenario.get("id") not in scenario_filter
):
logging.info(
f"Skipping scenario {expanded_scenario.get('id')} (filtered)"
)
continue
yield {
"scenario": expanded_scenario,
"group_id": group_id,
"group_description": group_description,
"config_set": self.current_config_set,
"config_suffix": self.config_suffix,
}
def _build_benchmark_command(
self,
scenario: dict,
*,
tls: Optional[bool] = None,
seed_val: Optional[int] = None,
warmup_mode: bool = False,
port: Optional[int] = None,
cpu_range: Optional[str] = None,
) -> List[str]:
"""Build argv for a predefined ``test`` or arbitrary ``command``.
``seed_val`` shares a seed across related invocations; when omitted,
each invocation draws one unless seeding is disabled.
"""
cmd = []
cores = cpu_range or self.cores
if cores:
cmd += ["taskset", "-c", cores]
cmd.append(self.valkey_benchmark_path)
use_tls = tls if tls is not None else self.tls_mode
if use_tls:
cmd += ["--tls"]
cmd += ["--cert", "./tests/tls/valkey.crt"]
cmd += ["--key", "./tests/tls/valkey.key"]
cmd += ["--cacert", "./tests/tls/ca.crt"]
cmd += ["-h", self.target_ip]
cmd += ["-p", str(port or self.config.get("port", DEFAULT_PORT))]
keyspacelen_val = scenario.get(
"keyspacelen", self.config.get("keyspacelen", [1000000])[0]
)
if "test" in scenario:
if warmup_mode:
cmd += ["--duration", str(scenario.get("warmup", 60))]
elif scenario.get("duration") is not None:
cmd += ["--duration", str(scenario["duration"])]
elif scenario.get("requests") is not None:
cmd += ["-n", str(scenario["requests"])]
else:
raise ValueError(
f"test scenario {scenario.get('id')!r} requires "
"'requests' or 'duration'"
)
cmd += ["-r", str(keyspacelen_val)]
if scenario.get("data_size") is not None:
cmd += ["-d", str(scenario["data_size"])]
cmd += ["-P", str(scenario.get("pipeline", 1))]
cmd += ["-c", str(scenario.get("clients", 1))]
cmd += ["-t", scenario["test"]]
if self.benchmark_threads is not None:
cmd += ["--threads", str(self.benchmark_threads)]
# Inline warmup is distinct from the scenario's pre-run warmup.
warmup_inline = scenario.get("warmup_inline")
if not warmup_mode and warmup_inline is not None and warmup_inline > 0:
cmd += ["--warmup", str(warmup_inline)]
else:
if scenario.get("dataset"):
dataset_path = Path(scenario["dataset"])
if not dataset_path.is_absolute():
dataset_path = Path.cwd() / dataset_path
cmd += ["--dataset", str(dataset_path)]
if scenario.get("xml_root_element"):
cmd += ["--xml-root-element", scenario["xml_root_element"]]
if scenario.get("maxdocs") and scenario.get("type") == "write":
cmd += ["--maxdocs", str(scenario["maxdocs"])]
if warmup_mode:
warmup_duration = scenario.get("warmup", 60)
cmd += ["--duration", str(warmup_duration)]
else:
if scenario.get("duration"):
cmd += ["--duration", str(scenario["duration"])]
elif scenario.get("requests"):
cmd += ["-n", str(scenario["requests"])]
elif scenario.get("maxdocs"):
cmd += ["-n", str(scenario["maxdocs"])]
else:
cmd += ["--duration", str(self.config.get("duration", 60))]
cmd += ["-c", str(scenario.get("clients", 1))]
cmd += ["-P", str(scenario.get("pipeline", 1))]
cmd += ["-r", str(keyspacelen_val)]
if scenario.get("data_size") is not None:
cmd += ["-d", str(scenario["data_size"])]
if self.benchmark_threads is not None:
cmd += ["--threads", str(self.benchmark_threads)]
if scenario.get("sequential", False):
cmd += ["--sequential"]
if self._should_add_cluster_flag(scenario):
cmd += ["--cluster"]
if scenario.get("seed") is not False and self.config.get("seed") is not False:
seed = seed_val if seed_val is not None else random.randint(0, 1000000)
cmd += ["--seed", str(seed)]
cmd += ["--csv"]
if "command" in scenario:
cmd += ["--"]
cmd += shlex.split(scenario["command"])
return cmd
def _find_csv_start(self, lines: List[str]) -> Optional[int]:
"""Find CSV header line index."""
for i, line in enumerate(lines):
if line.startswith('"test","rps"') or line.startswith("test,rps"):
return i
return None
def _parse_csv_row(self, stdout: str) -> Optional[dict]:
"""Parse benchmark CSV output, return first row."""
if not stdout:
return None
lines = stdout.splitlines()
csv_start = self._find_csv_start(lines)
if csv_start is None:
return None
reader = csv.DictReader(lines[csv_start:])
for row in reader:
return row
return None
def _parse_csv_row_for_test(self, stdout: str, test_name: str) -> Optional[dict]:
"""Parse CSV output of a predefined ``-t`` workload.
``valkey-benchmark -t CMD`` emits rows whose test name may be a
variant of the command (e.g. ``MSET (10 keys)``), so the first row
whose test name starts with the benchmarked name is returned.
"""
if not stdout:
return None
lines = stdout.splitlines()
csv_start = self._find_csv_start(lines)
if csv_start is None:
return None
for row in csv.DictReader(lines[csv_start:]):
if row.get("test", "").startswith(test_name):
return row
return None
def _is_cme(self) -> bool:
"""Check if cluster mode is enabled with multiple nodes."""
return self.cluster_mode and self.config.get("cluster_nodes", 1) > 1
def _should_use_parallel(self, scenario: dict) -> bool:
"""Determine if scenario should use parallel execution."""
return (
self._is_cme() and scenario.get("cluster_execution", "single") == "parallel"
)
def _expand_scenario_options(self, scenario: dict) -> List[dict]:
"""Expand option variants, applying mixed options to read children."""
options = scenario.get("options")
if not options:
return [scenario]
scenarios = []
for flag, suffix in options.items():
variant = copy.deepcopy(scenario)
variant["id"] = scenario["id"] + suffix
if variant.get("type") == "mixed":
for read in variant.get("reads", []):
# options append a benchmark flag to an arbitrary command
# string; a predefined ``test:`` read has no command string
# to extend, so leave it untouched.
if flag and "command" in read:
read["command"] = read["command"] + f" {flag}"
else:
variant["command"] = scenario["command"] + (f" {flag}" if flag else "")
if "description" in variant and flag:
variant["description"] += f" + {flag}"
scenarios.append(variant)
return scenarios
def _apply_row_metadata(
self,
metrics: dict,
*,
test_id: str,
test_phase: str,
group_id,
scenario_id: str,
config_set: dict,
group_description: Optional[str] = None,
scenario_description: Optional[str] = None,
dataset: Optional[str] = None,
) -> None:
"""Stamp shared scenario identity fields onto ``metrics`` in place.
Optional fields remain absent when unset so success and failure rows
have identical comparison keys.
"""
metrics["test_id"] = test_id
metrics["test_phase"] = test_phase
metrics["group"] = group_id
metrics["scenario"] = scenario_id
metrics["config_set"] = config_set
if group_description:
metrics["group_description"] = group_description
if scenario_description:
metrics["scenario_description"] = scenario_description
if self.config_name:
metrics["config_name"] = self.config_name
if self.module_commit:
metrics["module_commit"] = self.module_commit
if self.module_commit_timestamp:
metrics["module_commit_timestamp"] = self.module_commit_timestamp
if dataset:
metrics["dataset"] = dataset
def _create_failure_marker(
self,
metrics_processor,
workload: dict,
*,
group_id,
scenario_id: str,
test_id: str,
test_phase: str,
error: str,
config_set: Optional[dict] = None,
requests: Optional[int] = None,
warmup: Optional[int] = None,
parent_scenario: Optional[dict] = None,
group_description: Optional[str] = None,
) -> dict:
"""Build a failed row with identity metadata but no performance fields.
Mixed children inherit duration and description from their parent.
"""
parent = parent_scenario or workload
marker = metrics_processor.build_base_metadata(
workload.get("command") or workload.get("test", ""),
workload.get("data_size", 100),
workload.get("pipeline", 1),
workload.get("clients", 1),
requests=requests,
warmup=warmup,
duration=workload.get("duration") or parent.get("duration"),
)
marker["status"] = "failed"
marker["error"] = error
self._apply_row_metadata(
marker,
test_id=test_id,
test_phase=test_phase,
group_id=group_id,
scenario_id=scenario_id,
config_set=config_set if config_set is not None else {},
group_description=group_description,
scenario_description=parent.get("description"),
dataset=workload.get("dataset"),
)
return marker
def _setup_profiling_and_metrics(self, profiling_set: dict, commit_time: str):
"""Setup profiler and metrics processor based on profiling_set."""
profiling_enabled = profiling_set.get("enabled", False)
profiler = None
if profiling_enabled:
profiler = PerformanceProfiler(
results_dir=self.results_dir,
enabled=True,
config={"profiling": profiling_set},
commit_id="",
)
metrics_processor = None
if not profiling_enabled:
env_metadata = collect_environment_metadata(
benchmark_path=self.valkey_benchmark_path,
server_cpu_range=self.config.get("server_cpu_range"),
client_cpu_range=self.cores,
)
metrics_processor = MetricsProcessor(
self.commit_id,
self.cluster_mode,
self.tls_mode,
commit_time,
self.io_threads,
self.benchmark_threads,
self.architecture,
self.repository,
environment_metadata=env_metadata,
)
return profiler, metrics_processor, profiling_enabled
def _finalize_metrics(self, metrics_processor, metric_json, profiling_enabled):
"""Write metrics and log completion status."""
if metrics_processor and metric_json:
metrics_processor.write_metrics(self.results_dir, metric_json)
logging.info(
f"=== Benchmark Complete: {len(metric_json)} metrics collected ==="
)
elif profiling_enabled:
logging.info(
"=== Benchmark Complete: Profiling mode, no metrics collected ==="
)
else:
logging.warning("No metrics collected")
def _run_single_scenario(
self,
scenario,
group_id,
profiler,
metrics_processor,
config_set,
config_suffix,
group_description=None,
):
"""Run one scenario and return its metric row(s)."""
scenario_type = scenario.get("type", "test")
scenario_id = scenario.get("id", "unknown")
origin_simple = scenario.get(ORIGIN_FIELD) == ORIGIN_SIMPLE
logging.info(f"Running scenario: {scenario_id} (type: {scenario_type})")
self._prepare_server_state(scenario, config_set)
seed_val = self._draw_scenario_seed(scenario, origin_simple)
effective_profiling = self._resolve_effective_profiling(scenario)
scenario_profiling_enabled = effective_profiling.get("enabled", False)
profile_id = f"group{group_id}_{scenario_type}_{scenario_id}_{config_suffix}"
warmup_duration = scenario.get("warmup", 0)
try:
# Population failures follow the scenario's normal error policy.
self._populate_scenario_keyspace(scenario, seed_val)
self._run_scenario_warmup(scenario, group_id, config_set)
self._start_scenario_profiling(
profiler, scenario_profiling_enabled, effective_profiling, profile_id
)
# This finally is the single profiling teardown path.
try:
if scenario_type == "mixed":
logging.info(f"Running mixed workload for scenario {scenario_id}")
metrics_list = self._run_mixed_workload(
scenario,
group_id,
config_set,
metrics_processor,
warmup_duration,
group_description=group_description,
)
return metrics_list if metrics_list else None
# Invocation errors reach the outer scenario error policy.
proc, aggregated_row = self._execute_benchmark_run(scenario, seed_val)
if proc is None and aggregated_row is None:
logging.error(f"Benchmark failed for scenario {scenario_id}")
# Basic metrics omit scenario-schema failure markers.
if metrics_processor and not origin_simple:
return self._create_failure_marker(
metrics_processor,
scenario,
group_id=group_id,
scenario_id=scenario_id,
test_id=f"{group_id}_{scenario_id}",
test_phase=scenario_type,
error="No results",
config_set=config_set,
requests=scenario.get("requests")
or scenario.get("maxdocs"),
warmup=scenario.get("warmup_inline", warmup_duration),
group_description=group_description,
)
return None
if proc:
logging.info(f"Benchmark output:\n{proc.stdout}")
# Basic parse failures skip one combination; other scenarios
# emit a failure marker through the outer handler.
try:
return self._build_scenario_metrics(
scenario,
proc,
aggregated_row,
group_id,
config_set,
warmup_duration,
group_description,
metrics_processor,
)
except Exception as e:
if origin_simple:
logging.error(
f"Failed to parse benchmark results for scenario "
f"{group_id}_{scenario_id}: {e}"
)
return None
raise
finally:
self._stop_scenario_profiling(
profiler, scenario_profiling_enabled, profile_id
)
except Exception as e:
if origin_simple:
raise
logging.error(f"Scenario {group_id}_{scenario_id} failed: {e}")
if metrics_processor:
return self._create_failure_marker(
metrics_processor,
scenario,
group_id=group_id,
scenario_id=scenario_id,
test_id=f"{group_id}_{scenario_id}",
test_phase=scenario_type,
error=str(e),
config_set=config_set,
requests=scenario.get("requests") or scenario.get("maxdocs"),
warmup=scenario.get("warmup_inline", warmup_duration),
group_description=group_description,
)
return None
def _prepare_server_state(self, scenario, config_set):
"""Clean server state before a scenario runs, then run setup commands.
Restart when a launcher is available; otherwise flush the database.
"""
if scenario.get("restart_before", False) or scenario.get("flush_before", False):
if self.server_launcher:
self._restart_server()
# Re-apply config_set after restart since CONFIG SET values are lost
if config_set:
self._apply_config_set(config_set)
else:
self._flush_database()
for setup_cmd in scenario.get("setup_commands", []):
self._execute_setup_command(setup_cmd)
def _draw_scenario_seed(self, scenario, origin_simple):
"""Draw one seed shared by a populate pass and its main run."""
if origin_simple or scenario.get("populate_with"):
seed_val = random.randint(0, 1000000)
logging.info(f"Using seed value: {seed_val}")
return seed_val
return None
def _populate_scenario_keyspace(self, scenario, seed_val):
"""Seed a scenario's keyspace through its configured write workload."""
populate_with = scenario.get("populate_with")
if not populate_with:
return
keyspacelen_val = scenario.get(
"keyspacelen", self.config.get("keyspacelen", [1000000])[0]
)
populate_requests = (
scenario["requests"]
if scenario.get("requests") is not None
else keyspacelen_val
)
workload_key = "command" if "command" in scenario else "test"
self._populate_keyspace(
workload_key,
populate_with,
populate_requests,
keyspacelen_val,
scenario.get("data_size", 100),
scenario.get("pipeline", 1),
scenario.get("clients", 1),
seed_val,
)
def _resolve_effective_profiling(self, scenario):
"""Merge a scenario's profiling override onto the current profiling set."""
if scenario.get("profiling"):
return deep_merge(self.current_profiling_set, scenario["profiling"])
return self.current_profiling_set
def _run_scenario_warmup(self, scenario, group_id, config_set):
"""Run the scenario-shaped warmup pass and discard its results."""
warmup_duration = scenario.get("warmup", 0)
if warmup_duration <= 0:
return
scenario_type = scenario.get("type", "test")
if scenario_type == "mixed":
warmup_scenario = copy.deepcopy(scenario)
warmup_scenario["duration"] = warmup_duration
# Opt-in: warm only the write side. Reads during warmup query a cold
# keyspace, are discarded anyway, and consume client capacity that
# could be populating. Absent/false keeps today's full mixed warmup
# exactly, so configs relying on it to warm read-path state (e.g. the
# FTS scenario "j") are unaffected.
if warmup_scenario.get("warmup_writes_only"):
warmup_scenario["reads"] = []
logging.info(f"Running mixed warmup (writes only): {warmup_duration}s")
else:
logging.info(f"Running mixed warmup: {warmup_duration}s")
self._run_mixed_workload(
warmup_scenario,
group_id,
config_set,
metrics_processor=None,
warmup_duration=0,
)
elif self._should_use_parallel(scenario):
logging.info(
f"Running parallel warmup on {len(self._get_active_ports())} nodes: {warmup_duration}s"
)
self._run_parallel_search(
scenario,
self._get_active_ports(),
self.client_cpu_ranges,
warmup_mode=True,
)
else:
logging.info(f"Running warmup: {warmup_duration}s")
cpu = self.client_cpu_ranges[0] if self.client_cpu_ranges else None
self._run(
self._build_benchmark_command(
scenario=scenario, warmup_mode=True, cpu_range=cpu
),
cwd=self.valkey_path,
capture_output=True,
timeout=None,
)
def _start_scenario_profiling(
self, profiler, scenario_profiling_enabled, effective_profiling, profile_id
):
"""Start profiling for a scenario when a profiler is enabled."""
if profiler and scenario_profiling_enabled:
target_port = self._get_active_ports()[0] if self._is_cme() else None
if target_port:
logging.info(f"CME profiling: targeting node 0 on port {target_port}")
# Pass scenario delays override
profiler.delays = effective_profiling.get("delays", profiler.delays)
profiler.start_profiling(
profile_id, target_process="valkey-server", target_port=target_port
)
def _stop_scenario_profiling(
self, profiler, scenario_profiling_enabled, profile_id
):
"""Stop profiling for a scenario when a profiler is enabled."""
if profiler and scenario_profiling_enabled:
profiler.stop_profiling(profile_id)
def _execute_benchmark_run(self, scenario, seed_val):
"""Return a process or an aggregated row for a non-mixed scenario."""
if self._should_use_parallel(scenario):
logging.info(
f"Using parallel execution for scenario {scenario.get('id', 'unknown')}"
)
aggregated_row = self._run_parallel_search(
scenario,
self._get_active_ports(),
self.client_cpu_ranges,
seed_val=seed_val,
)
return None, aggregated_row