Repository navigation
Expand file tree
/
Copy path09_stackoverflow_graph_oltp.py
More file actions
10170 lines (9535 loc) · 409 KB
/
Copy path09_stackoverflow_graph_oltp.py
File metadata and controls
10170 lines (9535 loc) · 409 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 python3
"""
Example 09: Stack Overflow Graph (OLTP)
Builds a Stack Overflow property graph (Phase 2 schema) and runs an OLTP
workload on ArcadeDB and LadybugDB with the same operation mix as Example 08.
Threading note: Databases can exhibit different scaling behavior as thread
count increases. For cross-database comparability, run with --threads 1.
"""
import argparse
import collections
import concurrent.futures
import contextlib
import csv
import json
import os
import pickle
import random
import re
import shutil
import sqlite3
import subprocess
import sys
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
try:
from lxml import etree
except ImportError:
print("Missing dependency: lxml")
print("Install with: uv add lxml")
sys.exit(1)
# The uv release the containers download: the version the repo's CI pins (.github/workflows/test-native.yml UV_VERSION),
# fetched straight from its release URL instead of asking the GitHub API for "latest" (unpinned, and rate-limited for anonymous use).
UV_VERSION = "0.12.0"
def uv_bootstrap_commands(python_cmd: str) -> List[str]:
return [
(
f'{python_cmd} -c "import json, pathlib, platform, shutil, tarfile, urllib.request; '
"arch={'x86_64':'x86_64-unknown-linux-gnu','amd64':'x86_64-unknown-linux-gnu','aarch64':'aarch64-unknown-linux-gnu','arm64':'aarch64-unknown-linux-gnu'}[platform.machine().lower()]; "
f"version='{UV_VERSION}'; "
"archive=pathlib.Path('/tmp/uv.tar.gz'); "
"archive.write_bytes(urllib.request.urlopen(f'https://github.com/astral-sh/uv/releases/download/{version}/uv-{arch}.tar.gz', timeout=30).read()); "
"target=pathlib.Path('/tmp/uv-extract'); target.mkdir(parents=True, exist_ok=True); "
"tarfile.open(archive, 'r:gz').extractall(target); "
"uv_bin=next(p for p in target.rglob('uv') if p.is_file()); "
"pathlib.Path('/tmp/uv-bin').mkdir(parents=True, exist_ok=True); "
"shutil.copy2(uv_bin, '/tmp/uv-bin/uv')\""
),
'export PATH="/tmp/uv-bin:$PATH"',
]
EXPECTED_DATASETS = {
"stackoverflow-tiny",
"stackoverflow-small",
"stackoverflow-medium",
"stackoverflow-large",
"stackoverflow-xlarge",
"stackoverflow-full",
}
BENCHMARK_SCOPE_NOTE = (
"Scope: OLTP throughput/stability benchmark. "
"ArcadeDB, Ladybug, GraphQLite, SQLite native, and Python in-memory use the "
"same logical schema, "
"ID indexing, ingestion dataset/relationships, and CRUD operation mix. "
"Query language and execution path remain engine-native."
)
DEFAULT_OLTP_MIX = {
"read": 0.60,
"update": 0.20,
"insert": 0.10,
"delete": 0.10,
}
SQLITE_PROFILE_CHOICES = ["fair", "perf", "olap"]
def mem_limit_tag(mem_limit: str) -> str:
normalized = re.sub(r"[^0-9a-z]+", "", mem_limit.lower())
return f"mem{normalized}" if normalized else "memdefault"
def format_mib_as_docker_limit(mib: int) -> str:
return f"{max(1, int(mib))}m"
def split_total_memory_budget(
total_mem_limit: str, server_fraction: float
) -> tuple[str, str]:
total_mib = parse_size_to_mib(total_mem_limit)
server_mib = int(round(total_mib * server_fraction))
server_mib = max(1, min(total_mib - 1 if total_mib > 1 else 1, server_mib))
client_mib = max(1, total_mib - server_mib)
return format_mib_as_docker_limit(client_mib), format_mib_as_docker_limit(
server_mib
)
def split_total_cpu_budget(
total_cpus: float, server_fraction: float
) -> tuple[float, float]:
total = max(0.1, float(total_cpus))
if total <= 0.2:
half = total / 2.0
return half, total - half
server = total * server_fraction
min_share = min(0.5, total / 2.0)
server = max(min_share, min(total - min_share, server))
client = max(0.1, total - server)
return client, server
def format_cpu_quota(cpus: float) -> str:
value = max(0.01, float(cpus))
text = f"{value:.3f}".rstrip("0").rstrip(".")
return text if text else "0.01"
def resolve_server_fraction(args) -> float:
fraction = float(getattr(args, "server_fraction", 0.8))
if not 0.0 < fraction < 1.0:
raise SystemExit("--server-fraction must be > 0 and < 1")
return fraction
def backend_server_budget(args) -> tuple[str, float]:
if args.db != "neo4j":
return args.mem_limit, float(args.threads)
if not is_running_in_docker():
return args.mem_limit, float(args.threads)
server_fraction = resolve_server_fraction(args)
_client_mem, server_mem = split_total_memory_budget(args.mem_limit, server_fraction)
_client_cpu, server_cpu = split_total_cpu_budget(
float(args.threads), server_fraction
)
return server_mem, server_cpu
def backend_client_budget(args) -> tuple[str, float]:
if args.db != "neo4j":
return args.mem_limit, float(args.threads)
server_fraction = resolve_server_fraction(args)
client_mem, _server_mem = split_total_memory_budget(args.mem_limit, server_fraction)
client_cpu, _server_cpu = split_total_cpu_budget(
float(args.threads), server_fraction
)
return client_mem, client_cpu
def budget_allocation_report(args) -> dict:
total_mem = args.mem_limit
total_cpus = float(args.threads)
report = {
"model": "single_global_budget",
"db": args.db,
"total": {
"memory_limit": total_mem,
"cpus": format_cpu_quota(total_cpus),
"threads_input": args.threads,
},
}
if args.db == "neo4j" and is_running_in_docker():
server_fraction = resolve_server_fraction(args)
client_mem, server_mem = split_total_memory_budget(total_mem, server_fraction)
client_cpu, server_cpu = split_total_cpu_budget(total_cpus, server_fraction)
report["split"] = {
"client_fraction": round(1.0 - server_fraction, 2),
"server_fraction": round(server_fraction, 2),
"wrapper_client_allocation": {
"memory_limit": client_mem,
"cpus": format_cpu_quota(client_cpu),
},
"server_allocation": {
"memory_limit": server_mem,
"cpus": format_cpu_quota(server_cpu),
},
}
else:
report["split"] = {
"client_fraction": 1.0,
"server_fraction": 0.0,
"single_runtime_allocation": {
"memory_limit": total_mem,
"cpus": format_cpu_quota(total_cpus),
},
}
return report
READ_TARGET_KINDS = [
"user",
"question",
"answer",
"badge",
"tag",
"comment",
"edge_sample",
]
UPDATE_TARGET_KINDS = [
"question",
"answer",
"comment",
"user",
"tag",
"asked_edge",
"answered_edge",
"commented_on_edge",
"commented_on_answer_edge",
"earned_edge",
"linked_to_edge",
]
INSERT_TARGET_KINDS = [
"user_question",
"answer",
"comment",
"badge",
"tag_link",
"post_link",
"accepted_answer",
]
DELETE_TARGET_KINDS = [
"question",
"answer",
"comment",
"badge",
"user",
"tag",
"asked_edge",
"answered_edge",
"has_answer_edge",
"accepted_answer_edge",
"tagged_with_edge",
"commented_on_edge",
"commented_on_answer_edge",
"earned_edge",
"linked_to_edge",
]
ARCADE_VERTEX_TYPES = ["User", "Question", "Answer", "Tag", "Badge", "Comment"]
ARCADE_EDGE_TYPES = [
"ASKED",
"ANSWERED",
"HAS_ANSWER",
"ACCEPTED_ANSWER",
"TAGGED_WITH",
"COMMENTED_ON",
"COMMENTED_ON_ANSWER",
"EARNED",
"LINKED_TO",
]
LADYBUG_VERTEX_TYPES = ARCADE_VERTEX_TYPES
LADYBUG_EDGE_TYPES = [
"ASKED",
"ANSWERED",
"HAS_ANSWER",
"ACCEPTED_ANSWER",
"TAGGED_WITH",
"COMMENTED_ON",
"COMMENTED_ON_ANSWER",
"EARNED",
"LINKED_TO",
]
NEO4J_COMMUNITY_IMAGE = os.environ.get(
"ARCADEDB_BENCH_NEO4J_IMAGE",
"neo4j:community",
)
NEO4J_USERNAME = "neo4j"
NEO4J_PASSWORD = "arcadedb-bench"
NEO4J_DATABASE = "neo4j"
def get_arcadedb_module():
try:
import arcadedb
from arcadedb.exceptions import ArcadeDBError
except ImportError:
return None, None
return arcadedb, ArcadeDBError
def get_ladybug_module():
try:
import ladybug as lb
except ImportError:
return None
return lb
def get_graphqlite_module():
try:
import graphqlite
except ImportError:
return None
return graphqlite
def get_duckdb_module():
try:
import duckdb
except ImportError:
return None
return duckdb
def get_neo4j_module():
try:
import neo4j
except ImportError:
return None
return neo4j
def parse_int(value: Optional[str]) -> Optional[int]:
if value is None or value == "":
return None
try:
return int(value)
except ValueError:
return None
def parse_datetime(value: Optional[str]) -> Optional[datetime]:
if not value:
return None
try:
return datetime.fromisoformat(value.replace("Z", ""))
except ValueError:
return None
def to_epoch_millis(value: Optional[datetime]) -> Optional[int]:
if value is None:
return None
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return int(value.timestamp() * 1000)
def format_bytes_binary(value: int) -> str:
for unit in ["B", "KiB", "MiB", "GiB", "TiB"]:
if value < 1024:
return f"{value:.1f}{unit}"
value /= 1024
return f"{value:.1f}PiB"
def get_dir_size_bytes(path: Path) -> int:
total = 0
if not path.exists():
return 0
for root, _, files in os.walk(path):
for name in files:
total += (Path(root) / name).stat().st_size
return total
DOCKER_MEM_USAGE_RE = re.compile(
r"^\s*([0-9]*\.?[0-9]+)\s*([kmgt]?i?b|b)\s*$",
re.IGNORECASE,
)
def current_process_rss_kb() -> int:
try:
with open("/proc/self/status", "r", encoding="utf-8") as handle:
for line in handle:
if line.startswith("VmRSS:"):
parts = line.split()
if len(parts) >= 2:
return int(parts[1])
break
except FileNotFoundError:
pass
return 0
def parse_memory_usage_to_kb(value: str) -> int:
match = DOCKER_MEM_USAGE_RE.match(value.strip())
if not match:
return 0
amount = float(match.group(1))
unit = match.group(2).lower()
scale = {
"b": 1 / 1024,
"kib": 1,
"kb": 1,
"mib": 1024,
"mb": 1024,
"gib": 1024 * 1024,
"gb": 1024 * 1024,
"tib": 1024 * 1024 * 1024,
"tb": 1024 * 1024 * 1024,
}.get(unit)
if scale is None:
return 0
return int(amount * scale)
def docker_container_rss_kb(container_name: str) -> int:
docker = shutil.which("docker")
if not docker or not container_name:
return 0
result = subprocess.run(
[docker, "stats", "--no-stream", "--format", "{{.MemUsage}}", container_name],
check=False,
capture_output=True,
text=True,
)
if result.returncode != 0:
return 0
output = result.stdout.strip()
if not output:
return 0
usage = output.split("/", 1)[0].strip()
return parse_memory_usage_to_kb(usage)
def start_combined_rss_sampler(
extra_kb_sampler: Optional[Callable[[], int]] = None,
interval_sec: float = 1.0,
) -> Tuple[threading.Event, dict, threading.Thread]:
stop_event = threading.Event()
state = {
"client_max_kb": 0,
"server_max_kb": 0,
"combined_max_kb": 0,
}
def run():
while not stop_event.is_set():
client_kb = current_process_rss_kb()
server_kb = extra_kb_sampler() if extra_kb_sampler is not None else 0
state["client_max_kb"] = max(state["client_max_kb"], client_kb)
state["server_max_kb"] = max(state["server_max_kb"], server_kb)
state["combined_max_kb"] = max(
state["combined_max_kb"],
client_kb + server_kb,
)
time.sleep(interval_sec)
thread = threading.Thread(target=run, daemon=True)
thread.start()
return stop_event, state, thread
def start_rss_sampler(
interval_sec: float = 0.2,
) -> Tuple[threading.Event, dict, threading.Thread]:
stop_event = threading.Event()
state = {"max_kb": 0}
def run():
while not stop_event.is_set():
state["max_kb"] = max(state["max_kb"], current_process_rss_kb())
time.sleep(interval_sec)
thread = threading.Thread(target=run, daemon=True)
thread.start()
return stop_event, state, thread
class CsvTableWriter:
def __init__(self, path: Path, fieldnames: List[str], label: str):
self.path = path
self.fieldnames = fieldnames
self.label = label
self.row_count = 0
self.path.parent.mkdir(parents=True, exist_ok=True)
self.handle = self.path.open("w", encoding="utf-8", newline="")
self.writer = csv.DictWriter(self.handle, fieldnames=self.fieldnames)
self.writer.writeheader()
def write_rows(self, rows: List[Dict[str, Any]]) -> None:
if not rows:
return
for row in rows:
payload = {}
for key in self.fieldnames:
value = row.get(key)
if value is None:
payload[key] = ""
elif isinstance(value, str):
payload[key] = value.replace("\r", " ").replace("\n", " ")
else:
payload[key] = value
self.writer.writerow(payload)
self.row_count += 1
def close(self) -> None:
self.handle.close()
def iter_xml_rows(xml_path: Path) -> Iterable[Dict[str, str]]:
context = etree.iterparse(str(xml_path), events=("end",), tag="row")
for _, elem in context:
yield elem.attrib
elem.clear()
def parse_tags(tags_str: Optional[str]) -> List[str]:
if not tags_str:
return []
if "|" in tags_str:
return [t for t in tags_str.split("|") if t]
return [
t
for t in tags_str.replace(
"><",
"|",
)
.replace("<", "")
.replace(">", "")
.split("|")
if t
]
def choose_ops(count: int, mix: Dict[str, float], seed: int) -> List[str]:
rng = random.Random(seed)
return rng.choices(
population=["read", "update", "insert", "delete"],
weights=[mix["read"], mix["update"], mix["insert"], mix["delete"]],
k=count,
)
def run_with_retry(
action,
error_class,
max_retries: int = 100,
base_delay: float = 0.01,
max_delay: float = 0.5,
):
delay = base_delay
for attempt in range(max_retries):
try:
return action()
except error_class as exc:
if is_transient_record_not_found_error(exc):
raise
if attempt == max_retries - 1:
raise
time.sleep(delay)
delay = min(max_delay, delay * 2)
def is_transient_record_not_found_error(exc: Exception) -> bool:
def looks_like_not_found(text: str) -> bool:
lower = (text or "").lower()
if "recordnotfoundexception" in lower:
return True
if "record #" in lower and "not found" in lower:
return True
if "record not found" in lower:
return True
if "commandexecutionexception" in lower and "not found" in lower:
return True
return False
visited = set()
current: Optional[BaseException] = exc
while current is not None and id(current) not in visited:
visited.add(id(current))
if looks_like_not_found(str(current)):
return True
for arg in getattr(current, "args", ()):
if looks_like_not_found(str(arg)):
return True
current = getattr(current, "__cause__", None) or getattr(
current,
"__context__",
None,
)
return False
def create_arcadedb_schema(db):
for vertex_type in ("User", "Question", "Answer", "Tag", "Badge", "Comment"):
db.command("sql", f"CREATE VERTEX TYPE {vertex_type}")
db.command("sql", f"CREATE PROPERTY {vertex_type}.Id LONG")
for edge_type in (
"ASKED",
"ANSWERED",
"HAS_ANSWER",
"ACCEPTED_ANSWER",
"TAGGED_WITH",
"COMMENTED_ON",
"COMMENTED_ON_ANSWER",
"EARNED",
"LINKED_TO",
):
db.command("sql", f"CREATE EDGE TYPE {edge_type}")
db.async_executor().wait_completion()
def create_arcadedb_indexes(db):
db.command("sql", "CREATE INDEX ON User (Id) UNIQUE_HASH")
db.command("sql", "CREATE INDEX ON Question (Id) UNIQUE_HASH")
db.command("sql", "CREATE INDEX ON Answer (Id) UNIQUE_HASH")
db.command("sql", "CREATE INDEX ON Tag (Id) UNIQUE_HASH")
db.command("sql", "CREATE INDEX ON Badge (Id) UNIQUE_HASH")
db.command("sql", "CREATE INDEX ON Comment (Id) UNIQUE_HASH")
db.async_executor().wait_completion()
def create_ladybug_schema(conn):
conn.execute(
"CREATE NODE TABLE User(Id INT64 PRIMARY KEY, DisplayName STRING, Reputation INT64, CreationDate INT64, Views INT64, UpVotes INT64, DownVotes INT64)"
)
conn.execute(
"CREATE NODE TABLE Question(Id INT64 PRIMARY KEY, Title STRING, Body STRING, Score INT64, ViewCount INT64, CreationDate INT64, AnswerCount INT64, CommentCount INT64, FavoriteCount INT64)"
)
conn.execute(
"CREATE NODE TABLE Answer(Id INT64 PRIMARY KEY, Body STRING, Score INT64, CreationDate INT64, CommentCount INT64)"
)
conn.execute(
"CREATE NODE TABLE Tag(Id INT64 PRIMARY KEY, TagName STRING, Count INT64)"
)
conn.execute(
"CREATE NODE TABLE Badge(Id INT64 PRIMARY KEY, Name STRING, Date INT64, Class INT64)"
)
conn.execute(
"CREATE NODE TABLE Comment(Id INT64 PRIMARY KEY, Text STRING, Score INT64, CreationDate INT64)"
)
conn.execute("CREATE REL TABLE ASKED(FROM User TO Question, CreationDate INT64)")
conn.execute("CREATE REL TABLE ANSWERED(FROM User TO Answer, CreationDate INT64)")
conn.execute("CREATE REL TABLE HAS_ANSWER(FROM Question TO Answer)")
conn.execute("CREATE REL TABLE ACCEPTED_ANSWER(FROM Question TO Answer)")
conn.execute("CREATE REL TABLE TAGGED_WITH(FROM Question TO Tag)")
conn.execute(
"CREATE REL TABLE COMMENTED_ON(FROM Comment TO Question, CreationDate INT64, Score INT64)"
)
conn.execute(
"CREATE REL TABLE COMMENTED_ON_ANSWER(FROM Comment TO Answer, CreationDate INT64, Score INT64)"
)
conn.execute("CREATE REL TABLE EARNED(FROM User TO Badge, Date INT64, Class INT64)")
conn.execute(
"CREATE REL TABLE LINKED_TO(FROM Question TO Question, LinkTypeId INT64, CreationDate INT64)"
)
def arcadedb_insert_vertices(db, vertex_type: str, rows: List[Dict[str, Any]]):
if not rows:
return
parallel_flush = db.async_executor().get_parallel_level() > 1
with db.graph_batch(
batch_size=max(1, len(rows)),
expected_edge_count=0,
bidirectional=True,
commit_every=max(1, len(rows)),
use_wal=False,
parallel_flush=parallel_flush,
) as batch:
batch.create_vertices(vertex_type, rows)
def cypher_literal(value: Any) -> str:
if value is None:
return "null"
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, (int, float)):
return str(value)
text = str(value)
text = text.replace("\\", "\\\\").replace("'", "\\'")
return f"'{text}'"
def format_cypher_props(props: Dict[str, Any]) -> str:
if not props:
return ""
items = [f"{key}: {cypher_literal(value)}" for key, value in props.items()]
return "{" + ", ".join(items) + "}"
def format_counts_by_type(label: str, counts: Dict[str, int]) -> str:
parts = [f"{name}={value:,}" for name, value in counts.items()]
return f"{label}: " + ", ".join(parts)
VERIFY_SINGLE_THREAD_PROFILE = "v1_single_thread_series"
def normalize_count_dict(values: Optional[Dict[str, int]]) -> Dict[str, int]:
if not isinstance(values, dict):
return {}
normalized: Dict[str, int] = {}
for key, value in values.items():
try:
normalized[str(key)] = int(value)
except Exception:
normalized[str(key)] = 0
return normalized
def assert_count_dicts_match(
expected: Dict[str, int], actual: Dict[str, int], section: str, db_label: str
):
diffs = []
keys = sorted(set(expected.keys()) | set(actual.keys()))
for key in keys:
exp = int(expected.get(key, 0))
got = int(actual.get(key, 0))
if exp != got:
diffs.append(f"{section}.{key}: expected={exp}, actual={got}")
if diffs:
raise RuntimeError(
f"Deterministic single-thread CRUD verification failed for {db_label}:\n- "
+ "\n- ".join(diffs)
)
def verify_single_thread_series(
args: argparse.Namespace,
summary: Dict[str, Any],
db_label: str,
db_path: Path,
) -> Optional[Path]:
verify_dir = db_path
verify_dir.mkdir(parents=True, exist_ok=True)
dataset_tag = args.dataset.replace("-", "_")
baseline_path = (
verify_dir
/ f"verify_09_graph_oltp_{db_label}_{dataset_tag}_tx{args.transactions}_seed{args.seed}.json"
)
current_payload = {
"verification_profile": VERIFY_SINGLE_THREAD_PROFILE,
"dataset": args.dataset,
"transactions": int(args.transactions),
"seed": int(args.seed),
"threads": int(args.threads),
"node_count": int(summary.get("node_count") or 0),
"edge_count": int(summary.get("edge_count") or 0),
"node_counts_by_type": normalize_count_dict(summary.get("node_counts_by_type")),
"edge_counts_by_type": normalize_count_dict(summary.get("edge_counts_by_type")),
"op_counts": normalize_count_dict(summary.get("op_counts")),
}
def write_baseline() -> None:
baseline_payload = {
"meta": {
"created_at_utc": datetime.now(timezone.utc).strftime(
"%Y-%m-%dT%H:%M:%SZ"
),
"source_db": db_label,
},
"baseline": current_payload,
}
with open(baseline_path, "w", encoding="utf-8") as handle:
json.dump(baseline_payload, handle, indent=2, sort_keys=True)
if not baseline_path.exists():
write_baseline()
return baseline_path
with open(baseline_path, "r", encoding="utf-8") as handle:
existing = json.load(handle)
baseline = (existing or {}).get("baseline") or {}
if baseline.get("verification_profile") != VERIFY_SINGLE_THREAD_PROFILE:
write_baseline()
return baseline_path
if baseline.get("dataset") != current_payload["dataset"]:
raise RuntimeError(
"Deterministic verification baseline dataset mismatch: "
f"expected={baseline.get('dataset')} actual={current_payload['dataset']}"
)
if int(baseline.get("transactions") or 0) != current_payload["transactions"]:
raise RuntimeError(
"Deterministic verification baseline transactions mismatch: "
f"expected={baseline.get('transactions')} actual={current_payload['transactions']}"
)
if int(baseline.get("seed") or 0) != current_payload["seed"]:
raise RuntimeError(
"Deterministic verification baseline seed mismatch: "
f"expected={baseline.get('seed')} actual={current_payload['seed']}"
)
baseline_node_count = int(baseline.get("node_count") or 0)
baseline_edge_count = int(baseline.get("edge_count") or 0)
if baseline_node_count != current_payload["node_count"]:
raise RuntimeError(
"Deterministic single-thread CRUD verification failed "
f"for {db_label}: node_count expected={baseline_node_count}, actual={current_payload['node_count']}"
)
if baseline_edge_count != current_payload["edge_count"]:
raise RuntimeError(
"Deterministic single-thread CRUD verification failed "
f"for {db_label}: edge_count expected={baseline_edge_count}, actual={current_payload['edge_count']}"
)
assert_count_dicts_match(
normalize_count_dict(baseline.get("node_counts_by_type")),
current_payload["node_counts_by_type"],
"node_counts_by_type",
db_label,
)
assert_count_dicts_match(
normalize_count_dict(baseline.get("edge_counts_by_type")),
current_payload["edge_counts_by_type"],
"edge_counts_by_type",
db_label,
)
assert_count_dicts_match(
normalize_count_dict(baseline.get("op_counts")),
current_payload["op_counts"],
"op_counts",
db_label,
)
return baseline_path
def count_arcadedb_by_type(
db, vertex_types: List[str], edge_types: List[str]
) -> Tuple[Dict[str, int], Dict[str, int]]:
node_counts: Dict[str, int] = {}
edge_counts: Dict[str, int] = {}
for label in vertex_types:
rows = db.query("sql", f"SELECT count(*) AS count FROM {label}").to_list()
node_counts[label] = int(rows[0].get("count", 0)) if rows else 0
for label in edge_types:
rows = db.query("sql", f"SELECT count(*) AS count FROM {label}").to_list()
edge_counts[label] = int(rows[0].get("count", 0)) if rows else 0
return node_counts, edge_counts
def count_ladybug_by_type(
conn, vertex_types: List[str], edge_types: List[str]
) -> Tuple[Dict[str, int], Dict[str, int]]:
node_counts: Dict[str, int] = {}
edge_counts: Dict[str, int] = {}
for label in vertex_types:
rows = conn.execute(f"MATCH (n:{label}) RETURN count(n) AS count").get_all()
node_counts[label] = int(rows[0][0]) if rows else 0
for label in edge_types:
rows = conn.execute(
f"MATCH ()-[r:{label}]->() RETURN count(r) AS count"
).get_all()
edge_counts[label] = int(rows[0][0]) if rows else 0
return node_counts, edge_counts
def neo4j_container_name(db_path: Path) -> str:
raw = re.sub(r"[^a-z0-9]+", "-", db_path.name.lower()).strip("-")
return f"arcadedb-bench-{raw[:40]}-{os.getpid()}"
def neo4j_fix_dir_ownership(path: Path) -> None:
if not path.exists() or not hasattr(os, "getuid") or not hasattr(os, "getgid"):
return
docker = shutil.which("docker")
if not docker:
return
host_uid = os.getuid()
host_gid = os.getgid()
command = [
docker,
"run",
"--rm",
"--user",
"0:0",
"-v",
f"{path.resolve()}:/target",
"--entrypoint",
"sh",
NEO4J_COMMUNITY_IMAGE,
"-lc",
f"chown -R {host_uid}:{host_gid} /target",
]
subprocess.run(
command,
check=False,
capture_output=True,
text=True,
)
def neo4j_prepare_dirs(db_path: Path) -> Dict[str, Path]:
root = db_path / "neo4j_ce"
if root.exists():
neo4j_fix_dir_ownership(root)
shutil.rmtree(root)
paths = {
"root": root,
"data": root / "data",
"logs": root / "logs",
"import": root / "import",
"plugins": root / "plugins",
}
for path in paths.values():
path.mkdir(parents=True, exist_ok=True)
return paths
def neo4j_run_command(command: List[str], *, capture: bool = False) -> str:
result = subprocess.run(
command,
check=True,
capture_output=capture,
text=True,
)
return result.stdout.strip() if capture else ""
def start_neo4j_service(db_path: Path, mem_limit: str, cpus: float) -> Dict[str, Any]:
neo4j = get_neo4j_module()
if neo4j is None:
raise RuntimeError("neo4j Python driver is not installed")
docker = shutil.which("docker")
if not docker:
raise RuntimeError("docker is required for the Neo4j backend")
service_paths = neo4j_prepare_dirs(db_path)
container_name = neo4j_container_name(db_path)
total_mib = parse_size_to_mib(mem_limit)
heap_mib = max(256, int(total_mib * 0.50))
pagecache_mib = max(128, int(total_mib * 0.25))
connect_host = "host.docker.internal" if is_running_in_docker() else "127.0.0.1"
port_binding = "7687" if is_running_in_docker() else "127.0.0.1::7687"
subprocess.run(
[docker, "rm", "-f", container_name],
check=False,
capture_output=True,
text=True,
)
neo4j_run_command(
[
docker,
"run",
"-d",
"--rm",
"--name",
container_name,
"--user",
"0:0",
"--memory",
mem_limit,
"--cpus",
format_cpu_quota(cpus),
"-p",
port_binding,
"-e",
f"NEO4J_AUTH={NEO4J_USERNAME}/{NEO4J_PASSWORD}",
"-e",
f"NEO4J_server_memory_heap_initial__size={heap_mib}m",
"-e",
f"NEO4J_server_memory_heap_max__size={heap_mib}m",
"-e",
f"NEO4J_server_memory_pagecache_size={pagecache_mib}m",
"-e",
"NEO4J_server_default__listen__address=0.0.0.0",
"-v",
f"{service_paths['data'].resolve()}:/data",
"-v",
f"{service_paths['logs'].resolve()}:/logs",
"-v",
f"{service_paths['import'].resolve()}:/import",
"-v",
f"{service_paths['plugins'].resolve()}:/plugins",
NEO4J_COMMUNITY_IMAGE,