Repository navigation
Expand file tree
/
Copy path10_stackoverflow_graph_olap.py
More file actions
6961 lines (6373 loc) · 233 KB
/
Copy path10_stackoverflow_graph_olap.py
File metadata and controls
6961 lines (6373 loc) · 233 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 10: Stack Overflow Graph (OLAP)
Builds a Stack Overflow property graph (Phase 2 schema) and runs a fixed
OLAP query suite using OpenCypher.
"""
import argparse
import collections
import csv
import hashlib
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",
}
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 graph_olap_acceleration_mode(
db: str,
*,
use_gav: bool = False,
) -> str:
if db == "arcadedb_cypher":
return "gav" if use_gav else "off"
return "off"
def graph_olap_acceleration_enabled(
db: str,
*,
use_gav: bool = False,
) -> bool:
return (
graph_olap_acceleration_mode(
db,
use_gav=use_gav,
)
!= "off"
)
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
BENCHMARK_SCOPE_NOTE = (
"Scope: OLAP query fairness on a common query suite. "
"Ingestion paths differ by engine (ArcadeDB loads through GraphBatch, Ladybug uses staged CSV + COPY), "
"so load/index timings are not a same-path ingest comparison."
)
INDEX_DEFS: List[Tuple[str, List[str], bool]] = [
("User", ["Id"], True),
("Question", ["Id"], True),
("Answer", ["Id"], True),
("Tag", ["Id"], True),
("Badge", ["Id"], True),
("Comment", ["Id"], True),
]
VERTEX_TYPES = ["User", "Question", "Answer", "Tag", "Badge", "Comment"]
EDGE_TYPES = [
"ASKED",
"ANSWERED",
"HAS_ANSWER",
"ACCEPTED_ANSWER",
"TAGGED_WITH",
"COMMENTED_ON",
"COMMENTED_ON_ANSWER",
"EARNED",
"LINKED_TO",
]
GAV_NAME = "stackoverflowOlap"
GAV_QUERY_PROPERTIES = ["Id", "DisplayName", "TagName", "Name", "Score"]
NEO4J_COMMUNITY_IMAGE = os.environ.get(
"ARCADEDB_BENCH_NEO4J_IMAGE",
"neo4j:community",
)
NEO4J_USERNAME = "neo4j"
NEO4J_PASSWORD = "arcadedb-bench"
NEO4J_DATABASE = "neo4j"
QUERY_DEFS: List[Dict[str, str]] = [
{
"name": "top_askers",
"cypher": """
MATCH (u:User)-[:ASKED]->(q:Question)
RETURN u.Id AS user_id, u.DisplayName AS name, count(q) AS questions
ORDER BY questions DESC, user_id ASC
LIMIT 10
""",
},
{
"name": "top_answerers",
"cypher": """
MATCH (u:User)-[:ANSWERED]->(a:Answer)
RETURN u.Id AS user_id, u.DisplayName AS name, count(a) AS answers
ORDER BY answers DESC, user_id ASC
LIMIT 10
""",
},
{
"name": "top_accepted_answerers",
"cypher": """
MATCH (q:Question)-[:ACCEPTED_ANSWER]->(a:Answer)
MATCH (u:User)-[:ANSWERED]->(a)
WITH u, count(*) AS accepted
RETURN u.Id AS user_id, u.DisplayName AS name, accepted
ORDER BY accepted DESC, user_id ASC
LIMIT 10
""",
},
{
"name": "top_tags_by_questions",
"cypher": """
MATCH (q:Question)-[:TAGGED_WITH]->(t:Tag)
RETURN t.Id AS tag_id, t.TagName AS tag, count(q) AS questions
ORDER BY questions DESC, tag_id ASC
LIMIT 10
""",
},
{
"name": "tag_cooccurrence",
"cypher": """
MATCH (q:Question)-[:TAGGED_WITH]->(t1:Tag)
MATCH (q)-[:TAGGED_WITH]->(t2:Tag)
WHERE t1.Id < t2.Id
RETURN t1.TagName AS tag1, t2.TagName AS tag2, count(*) AS cooccurs
ORDER BY cooccurs DESC, tag1 ASC, tag2 ASC
LIMIT 10
""",
},
{
"name": "top_questions_by_score",
"cypher": """
MATCH (q:Question)
RETURN q.Id AS question_id, q.Score AS score
ORDER BY score DESC, question_id ASC
LIMIT 10
""",
},
{
"name": "questions_with_most_answers",
"cypher": """
MATCH (q:Question)-[:HAS_ANSWER]->(a:Answer)
RETURN q.Id AS question_id, count(a) AS answers
ORDER BY answers DESC, question_id ASC
LIMIT 10
""",
},
{
"name": "asker_answerer_pairs",
"cypher": """
MATCH (asker:User)-[:ASKED]->(q:Question)-[:HAS_ANSWER]->(a:Answer)<-[:ANSWERED]-(answerer:User)
WHERE asker.Id <> answerer.Id
WITH asker, answerer, count(*) AS interactions
RETURN asker.Id AS asker_id, answerer.Id AS answerer_id, interactions
ORDER BY interactions DESC, asker_id ASC, answerer_id ASC
LIMIT 10
""",
},
{
"name": "top_badges",
"cypher": """
MATCH (:User)-[:EARNED]->(b:Badge)
RETURN b.Name AS badge, count(*) AS earned
ORDER BY earned DESC, badge ASC
LIMIT 10
""",
},
# Luca is investigating the COUNT() optimization regression that breaks this query.
{
"name": "top_questions_by_total_comments",
"cypher": """
MATCH (q:Question)
OPTIONAL MATCH (c1:Comment)-[:COMMENTED_ON]->(q)
WITH q, count(c1) AS direct_comments
OPTIONAL MATCH (q)-[:HAS_ANSWER]->(a:Answer)
OPTIONAL MATCH (c2:Comment)-[:COMMENTED_ON_ANSWER]->(a)
WITH q, direct_comments, count(c2) AS answer_comments
RETURN q.Id AS question_id, direct_comments + answer_comments AS total_comments
ORDER BY total_comments DESC, question_id ASC
LIMIT 10
""",
},
]
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 configure_sqlite_profile(conn: sqlite3.Connection, profile: str) -> Dict[str, Any]:
profile = (profile or "olap").lower()
if profile not in SQLITE_PROFILE_CHOICES:
raise ValueError(
f"Unsupported sqlite profile: {profile}. "
f"Expected one of: {', '.join(SQLITE_PROFILE_CHOICES)}"
)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=30000")
conn.execute("PRAGMA temp_store=MEMORY")
if profile == "fair":
conn.execute("PRAGMA synchronous=FULL")
conn.execute("PRAGMA foreign_keys=ON")
elif profile == "perf":
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA foreign_keys=ON")
else:
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA foreign_keys=ON")
conn.execute("PRAGMA cache_size=-200000")
conn.execute("PRAGMA mmap_size=268435456")
return {
"profile": profile,
"journal_mode": "WAL",
"synchronous": "FULL" if profile == "fair" else "NORMAL",
"foreign_keys": "ON",
"temp_store": "MEMORY",
"busy_timeout_ms": 30000,
"cache_size_kib": 200000 if profile == "olap" else None,
"mmap_size_bytes": 268435456 if profile == "olap" else None,
}
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 get_retry_config(dataset_size: str) -> Dict[str, int]:
size = dataset_size.split("-")[-1] if "-" in dataset_size else dataset_size
configs = {
"tiny": {"retry_delay": 10, "max_retries": 60},
"small": {"retry_delay": 60, "max_retries": 120},
"medium": {"retry_delay": 180, "max_retries": 200},
"large": {"retry_delay": 300, "max_retries": 200},
}
return configs.get(size, configs["tiny"])
def count_arcadedb_by_type(db) -> 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(
"opencypher",
f"MATCH (n:{label}) RETURN count(n) AS count",
).to_list()
node_counts[label] = int(rows[0].get("count", 0)) if rows else 0
for label in EDGE_TYPES:
rows = db.query(
"opencypher",
f"MATCH ()-[r:{label}]->() RETURN count(r) AS count",
).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) -> 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,
]
)
bolt_port = neo4j_run_command(
[
docker,
"inspect",
"--format",
'{{(index (index .NetworkSettings.Ports "7687/tcp") 0).HostPort}}',
container_name,
],
capture=True,
)
if not bolt_port:
raise RuntimeError("Could not determine mapped Neo4j bolt port")
driver = neo4j.GraphDatabase.driver(
f"bolt://{connect_host}:{bolt_port}",
auth=(NEO4J_USERNAME, NEO4J_PASSWORD),
)
last_error: Optional[Exception] = None
deadline = time.time() + 120
while time.time() < deadline:
try:
with driver.session(database=NEO4J_DATABASE) as session:
session.run("RETURN 1 AS ready").single()
break
except Exception as exc:
last_error = exc
time.sleep(1)
else:
driver.close()
subprocess.run(
[docker, "rm", "-f", container_name],
check=False,
capture_output=True,
text=True,
)
raise RuntimeError(f"Timed out waiting for Neo4j to become ready: {last_error}")
return {
"driver": driver,
"container_name": container_name,
"paths": service_paths,
"bolt_port": int(bolt_port),
"host": connect_host,
"server_version": get_neo4j_server_version(driver),
}
def stop_neo4j_service(service: Optional[Dict[str, Any]]) -> None:
if not service:
return
driver = service.get("driver")
if driver is not None:
driver.close()
container_name = service.get("container_name")
if container_name and shutil.which("docker"):
subprocess.run(
["docker", "rm", "-f", str(container_name)],
check=False,
capture_output=True,
text=True,
)
service_paths = service.get("paths") or {}
root_path = service_paths.get("root")
if root_path is not None:
neo4j_fix_dir_ownership(Path(root_path))
def neo4j_execute_write(
driver,
query: str,
parameters: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
with driver.session(database=NEO4J_DATABASE) as session:
return session.execute_write(
lambda tx: list(tx.run(query, parameters or {}).data())
)
def neo4j_execute_read(
driver,
query: str,
parameters: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
with driver.session(database=NEO4J_DATABASE) as session:
return session.execute_read(
lambda tx: list(tx.run(query, parameters or {}).data())
)
def get_neo4j_server_version(driver) -> Optional[str]:
rows = neo4j_execute_read(
driver,
"CALL dbms.components() YIELD versions RETURN versions[0] AS version LIMIT 1",
)
if not rows:
return None
return str(rows[0].get("version")) if rows[0].get("version") is not None else None
def count_neo4j_by_type(driver) -> Tuple[Dict[str, int], Dict[str, int]]:
node_counts: Dict[str, int] = {}
edge_counts: Dict[str, int] = {}
for label in VERTEX_TYPES:
rows = neo4j_execute_read(driver, f"MATCH (n:{label}) RETURN count(n) AS count")
node_counts[label] = int(rows[0].get("count", 0)) if rows else 0
for label in EDGE_TYPES:
rows = neo4j_execute_read(
driver,
f"MATCH ()-[r:{label}]->() RETURN count(r) AS count",
)
edge_counts[label] = int(rows[0].get("count", 0)) if rows else 0
return node_counts, edge_counts
def collect_graph_counts_arcadedb(db) -> Dict[str, object]:
node_rows = db.query("opencypher", "MATCH (n) RETURN count(n) AS count").to_list()
edge_rows = db.query(
"opencypher", "MATCH ()-[r]->() RETURN count(r) AS count"
).to_list()
node_total = int(node_rows[0].get("count", 0)) if node_rows else 0
edge_total = int(edge_rows[0].get("count", 0)) if edge_rows else 0
node_counts, edge_counts = count_arcadedb_by_type(db)
return {
"node_total": node_total,
"edge_total": edge_total,
"node_counts_by_type": node_counts,
"edge_counts_by_type": edge_counts,
}
def create_arcadedb_gav(db, arcade_error) -> None:
vertex_types_sql = ", ".join(VERTEX_TYPES)
edge_types_sql = ", ".join(EDGE_TYPES)
property_sql = ", ".join(GAV_QUERY_PROPERTIES)
statement = (
f"CREATE GRAPH ANALYTICAL VIEW {GAV_NAME} "
f"VERTEX TYPES ({vertex_types_sql}) "
f"EDGE TYPES ({edge_types_sql}) "
f"PROPERTIES ({property_sql}) "
"UPDATE MODE OFF"
)
try:
db.command("sql", statement)
except arcade_error as exc:
raise RuntimeError(
"GAV was requested for Example 10, but Graph Analytical View SQL "
f"support is not available: {exc}"
) from exc
def fetch_arcadedb_gav_metadata(db, name: str) -> Optional[Dict[str, Any]]:
row = db.query(
"sql",
"SELECT FROM schema:graphAnalyticalViews WHERE name = ?",
name,
).first()
if row is None:
return None
return {
"name": row.get("name"),
"status": row.get("status"),
"updateMode": row.get("updateMode"),
"nodeCount": row.get("nodeCount"),
"edgeCount": row.get("edgeCount"),
"buildDurationMs": row.get("buildDurationMs"),
}
def wait_for_arcadedb_gav_status(
db,
name: str,
expected_statuses: set[str],
timeout_sec: float = 1800.0,
) -> Dict[str, Any]:
start = time.perf_counter()
last_metadata = None
while True:
metadata = fetch_arcadedb_gav_metadata(db, name)
if metadata is not None:
last_metadata = metadata
if metadata["status"] in expected_statuses:
return metadata
if time.perf_counter() - start > timeout_sec: