gql-core 0.2.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. benchmark/__init__.py +0 -0
  2. benchmark/cache/ldbc_snb_impls/postgres/scripts/load.py +78 -0
  3. benchmark/cache/ldbc_snb_impls/postgres/scripts/test-db-connection.py +12 -0
  4. benchmark/cache/ldbc_snb_impls/umbra/scripts/load.py +57 -0
  5. benchmark/cache/ldbc_snb_impls/umbra/scripts/test-db-connection.py +12 -0
  6. benchmark/gqlbench_eval.py +285 -0
  7. benchmark/logical_reasoning.py +191 -0
  8. benchmark/natural_queries.py +956 -0
  9. benchmark/nl_to_gql.py +484 -0
  10. benchmark/queries.py +141 -0
  11. benchmark/query_suite.py +1527 -0
  12. benchmark/run_nl_benchmark.py +287 -0
  13. benchmark/run_suite_benchmark.py +385 -0
  14. benchmark/snb/__init__.py +1 -0
  15. benchmark/snb/download_sf01.py +66 -0
  16. benchmark/snb/inventory.py +409 -0
  17. benchmark/snb/loader.py +321 -0
  18. benchmark/snb/oracle.py +366 -0
  19. benchmark/snb/runner.py +371 -0
  20. benchmark/snb/test_sf01_capacity.py +80 -0
  21. benchmark/tck/__init__.py +1 -0
  22. benchmark/tck/classifier.py +51 -0
  23. benchmark/tck/fixture_loader.py +190 -0
  24. benchmark/tck/gherkin_parser.py +912 -0
  25. benchmark/tck/runner.py +267 -0
  26. benchmark/tck/tck_adapter.py +782 -0
  27. benchmark/vs_sqlite.py +340 -0
  28. gql_core/__init__.py +185 -0
  29. gql_core/ai.py +228 -0
  30. gql_core/benchmark.py +402 -0
  31. gql_core/builder.py +530 -0
  32. gql_core/cli.py +369 -0
  33. gql_core/errors.py +23 -0
  34. gql_core/graph.py +449 -0
  35. gql_core/inference/__init__.py +35 -0
  36. gql_core/inference/engine.py +257 -0
  37. gql_core/inference/rules.py +119 -0
  38. gql_core/ingester.py +188 -0
  39. gql_core/ir.py +901 -0
  40. gql_core/mirror.py +220 -0
  41. gql_core/ontology/__init__.py +22 -0
  42. gql_core/ontology/model.py +75 -0
  43. gql_core/ontology/schema.py +246 -0
  44. gql_core/physical/__init__.py +16 -0
  45. gql_core/physical/engine.py +231 -0
  46. gql_core/physical/evaluator.py +1610 -0
  47. gql_core/physical/operators.py +500 -0
  48. gql_core/query/__init__.py +0 -0
  49. gql_core/query/ast.py +211 -0
  50. gql_core/query/cypher_temporal.py +1357 -0
  51. gql_core/query/executor.py +2098 -0
  52. gql_core/query/grammar.lark +216 -0
  53. gql_core/query/parser.py +1002 -0
  54. gql_core/query/planner.py +218 -0
  55. gql_core/query/semantic.py +1017 -0
  56. gql_core/query/static_types.py +387 -0
  57. gql_core/registry.py +283 -0
  58. gql_core/schema.py +27 -0
  59. gql_core/temporal.py +508 -0
  60. gql_core/types.py +172 -0
  61. gql_core/validator.py +142 -0
  62. gql_core/validator_ir.py +393 -0
  63. gql_core-0.2.0a1.dist-info/METADATA +226 -0
  64. gql_core-0.2.0a1.dist-info/RECORD +81 -0
  65. gql_core-0.2.0a1.dist-info/WHEEL +5 -0
  66. gql_core-0.2.0a1.dist-info/entry_points.txt +2 -0
  67. gql_core-0.2.0a1.dist-info/licenses/LICENSE +176 -0
  68. gql_core-0.2.0a1.dist-info/top_level.txt +5 -0
  69. graph/__init__.py +0 -0
  70. graph/store.py +424 -0
  71. ingestion/__init__.py +0 -0
  72. ingestion/cricsheet_parser.py +499 -0
  73. ingestion/ids.py +98 -0
  74. ingestion/validator.py +142 -0
  75. query/__init__.py +0 -0
  76. query/ast.py +95 -0
  77. query/executor.py +562 -0
  78. query/grammar.lark +90 -0
  79. query/parser.py +277 -0
  80. query/planner.py +209 -0
  81. query/semantic.py +241 -0
benchmark/__init__.py ADDED
File without changes
@@ -0,0 +1,78 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import os
4
+ import psycopg
5
+ import re
6
+ import time
7
+
8
+ class PostgresDbLoader():
9
+
10
+ def __init__(self):
11
+ self.database = os.environ.get("POSTGRES_DB", "ldbcsnb")
12
+ self.endpoint = os.environ.get("POSTGRES_HOST", "localhost")
13
+ self.port = int(os.environ.get("POSTGRES_PORT", 5432))
14
+ self.user = os.environ.get("POSTGRES_USER", "postgres")
15
+ self.password = os.environ.get("POSTGRES_PASSWORD", "mysecretpassword")
16
+
17
+
18
+ def run_script(self, conn, filename):
19
+
20
+ with open(filename, "r") as f:
21
+ try:
22
+ queries_file = f.read()
23
+ # strip comments
24
+ queries_file = re.sub(r"(\n|^)--.*", "", queries_file)
25
+ queries = queries_file.split(";")
26
+ for query in queries:
27
+ if query.isspace():
28
+ continue
29
+
30
+ sql_statement = re.findall(r"^((CREATE|INSERT|DROP|DELETE|SELECT|COPY|ALTER) [A-Za-z0-9_ ]*)", query, re.MULTILINE|re.IGNORECASE)
31
+ print(f"{sql_statement[0][0].strip()} ...")
32
+ start = time.time()
33
+ cur = conn.cursor()
34
+ cur.execute(query)
35
+ conn.commit()
36
+ end = time.time()
37
+ duration = end - start
38
+ print(f"-> {duration:.4f} seconds")
39
+ except Exception:
40
+ print(f"Error trying to execute query: {query};")
41
+ raise
42
+
43
+
44
+ def vacuum(self, conn):
45
+ conn.autocommit=True
46
+ conn.cursor().execute("ANALYZE")
47
+ conn.autocommit=False
48
+
49
+
50
+ def main(self):
51
+ with psycopg.connect(
52
+ dbname=self.database,
53
+ host=self.endpoint,
54
+ user=self.user,
55
+ password=self.password,
56
+ port=self.port
57
+ ) as conn:
58
+ print("Loading initial data set")
59
+ self.run_script(conn, "ddl/schema.sql")
60
+ self.run_script(conn, "ddl/load.sql")
61
+
62
+ print("Adding indexes and constraints")
63
+ self.run_script(conn, "ddl/schema_constraints.sql")
64
+ self.run_script(conn, "ddl/schema_foreign_keys.sql")
65
+
66
+ print("Vacuuming")
67
+ self.vacuum(conn)
68
+ conn.commit()
69
+ print("Loaded initial snapshot")
70
+
71
+ def load_script(self, filename):
72
+ with open(filename, "r") as f:
73
+ return f.read()
74
+
75
+
76
+ if __name__ == "__main__":
77
+ PGLoader = PostgresDbLoader()
78
+ PGLoader.main()
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import os
4
+ import psycopg
5
+
6
+ conn = psycopg.connect(
7
+ host=os.environ.get("POSTGRES_HOST", "localhost"),
8
+ user=os.environ.get("POSTGRES_USER", "postgres"),
9
+ password=os.environ.get("POSTGRES_PASSWORD", "mysecretpassword"),
10
+ port=int(os.environ.get("POSTGRES_PORT", 5432))
11
+ )
12
+ conn.close()
@@ -0,0 +1,57 @@
1
+ import psycopg
2
+ import re
3
+ import os
4
+ import time
5
+
6
+ class UmbraDbLoader():
7
+
8
+ def __init__(self):
9
+ self.database = os.environ.get("UMBRA_DATABASE", "ldbcsnb")
10
+ self.endpoint = os.environ.get("UMBRA_HOST", "localhost")
11
+ self.port = int(os.environ.get("UMBRA_PORT", 5432))
12
+ self.user = os.environ.get("UMBRA_USER", "postgres")
13
+ self.password = os.environ.get("UMBRA_PASSWORD", "mysecretpassword")
14
+
15
+ def load_data(self):
16
+ with psycopg.connect(
17
+ dbname=self.database,
18
+ host=self.endpoint,
19
+ user=self.user,
20
+ password=self.password,
21
+ port=self.port,
22
+ autocommit=True
23
+ ) as pg_con:
24
+
25
+ print("Load initial snapshot")
26
+ loader.run_script(pg_con, "ddl/load.sql")
27
+
28
+ print("Creating materialized views . . . ")
29
+ loader.run_script(pg_con, "ddl/schema_constraints.sql")
30
+ pg_con.commit()
31
+ print("Done.")
32
+
33
+ print("Loaded initial snapshot to Umbra.")
34
+
35
+
36
+ def run_script(self, pg_con, filename):
37
+ cur = pg_con.cursor()
38
+ with open(filename, "r") as f:
39
+ queries_file = f.read()
40
+ queries = queries_file.split(";")
41
+ for query in queries:
42
+ if query.isspace():
43
+ continue
44
+
45
+ sql_statement = re.findall(r"^((CREATE|INSERT|DROP|DELETE|SELECT|COPY) [A-Za-z0-9_ ]*)", query, re.MULTILINE)
46
+ print(f"{sql_statement[0][0].strip()} ...")
47
+
48
+ start = time.time()
49
+ cur.execute(query)
50
+ end = time.time()
51
+ duration = end - start
52
+ print(f"-> {duration:.4f} seconds")
53
+
54
+
55
+ if __name__ == "__main__":
56
+ loader = UmbraDbLoader()
57
+ loader.load_data()
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import os
4
+ import psycopg
5
+
6
+ conn = psycopg.connect(
7
+ host=os.environ.get("UMBRA_HOST", "localhost"),
8
+ user=os.environ.get("UMBRA_USER", "postgres"),
9
+ password=os.environ.get("UMBRA_PASSWORD", "mysecretpassword"),
10
+ port=int(os.environ.get("UMBRA_PORT", 5432))
11
+ )
12
+ conn.close()
@@ -0,0 +1,285 @@
1
+ """Evaluate GQL-Core grammar coverage against GQLBench's 25,332 queries.
2
+
3
+ Measures: parse success rate, failure reasons by category, coverage by
4
+ query feature (aggregation, multi-hop, RPQ, etc.).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ import sys
12
+ from collections import Counter
13
+ from pathlib import Path
14
+
15
+ # Use our parser directly
16
+ ROOT = Path(__file__).resolve().parent.parent
17
+ sys.path.insert(0, str(ROOT))
18
+
19
+ from lark import UnexpectedToken, UnexpectedCharacters, UnexpectedEOF
20
+
21
+ from gql_core.query.parser import parse as gql_parse
22
+
23
+
24
+ def normalize_gql(gql: str) -> str | None:
25
+ """Normalize a GQLBench Cypher query to GQL-Core syntax.
26
+
27
+ Returns None if the query uses features we fundamentally cannot support.
28
+ """
29
+ # Skip queries with unsupported multi-clause / procedure features
30
+ upper = gql.upper()
31
+ if re.search(r'\bWITH\b', upper):
32
+ return None # multi-clause WITH
33
+ if re.search(r'\bCALL\b', upper):
34
+ return None # procedure calls
35
+ if re.search(r'\bLET\b', upper):
36
+ return None # LET assignment
37
+ if re.search(r'\bCOLLECT\b', upper):
38
+ return None # subquery COLLECT
39
+ if re.search(r'DISTINCT', upper):
40
+ return None # COUNT(DISTINCT ...) not supported
41
+ if re.search(r'\bUNION\b', upper):
42
+ return None # UNION not supported
43
+ if re.search(r'\bOPTIONAL\b', upper):
44
+ return None # OPTIONAL MATCH not supported
45
+ if "=~" in gql:
46
+ return None # regex match operator
47
+ if re.search(r'\bEXISTS\b', upper):
48
+ return None # EXISTS subquery
49
+ if re.search(r'\bCASE\b', upper):
50
+ return None # CASE expression
51
+
52
+ # Normalizations
53
+ # 1. Strip backtick quoting: `identifier` -> identifier
54
+ normalized = re.sub(r'`([^`]+)`', r'\1', gql)
55
+
56
+ # 2. COUNT(*) -> COUNT(_) (use underscore as dummy var)
57
+ normalized = re.sub(r'COUNT\(\*\)', 'COUNT(_)', normalized)
58
+
59
+ # 3. <> -> !=
60
+ normalized = normalized.replace('<>', '!=')
61
+
62
+ # 4. Fix node patterns that lost their variable:
63
+ # MATCH (:Label) needs a variable -> MATCH (_x:Label)
64
+ # But only if there's no variable before the colon
65
+ normalized = re.sub(r'\(:(\w+)', r'(_:\1', normalized)
66
+
67
+ # 5. Fix the special pattern in GQLBench: MATCH (t2:Label)-[r:REL]->(t1:Label)
68
+ # This is actually our exact syntax, just with backticks removed
69
+
70
+ # 6. IS NULL DESC in ORDER BY -> remove IS NULL (our engine doesn't support NULL ordering)
71
+ normalized = re.sub(r'\s+IS\s+NULL\s+(DESC|ASC)', r' \1', normalized, flags=re.IGNORECASE)
72
+
73
+ # 7. Remove trailing semicolons
74
+ normalized = normalized.rstrip(';').strip()
75
+
76
+ # 8. Capitalize labels: our grammar requires PascalCase labels
77
+ # (:club) -> (:Club), but preserve variable names
78
+ # Match label after colon that starts with lowercase
79
+ def capitalize_label(m):
80
+ prefix = m.group(1) # : or :` (already stripped backticks)
81
+ label = m.group(2)
82
+ return prefix + label[0].upper() + label[1:]
83
+ normalized = re.sub(r'(:)([a-z][a-zA-Z0-9_]*)', capitalize_label, normalized)
84
+
85
+ # 9. Fix relation labels with lowercase: -[r:plays_for]-> -> -[r:Plays_for]->
86
+ def capitalize_rel_label(m):
87
+ prefix = m.group(1)
88
+ label = m.group(2)
89
+ suffix = m.group(3)
90
+ return prefix + label[0].upper() + label[1:] + suffix
91
+ normalized = re.sub(r'(-\[[a-zA-Z_0-9]*:)([a-z][a-zA-Z0-9_]*)([\]-])', capitalize_rel_label, normalized)
92
+
93
+ # 10. Handle MATCH with only backtick-removed labels at start of line after MATCH
94
+ # Fix: ensure node patterns have variables
95
+ # MATCH (:Label) -> MATCH (_:Label)
96
+ normalized = re.sub(r'MATCH\s+\(:', r'MATCH (_:', normalized)
97
+
98
+ # 11. ORDER BY before RETURN (GQLBench puts it in various orders)
99
+ # Our grammar requires: MATCH ... WHERE ... RETURN ... ORDER BY ... LIMIT
100
+ # GQLBench sometimes has: MATCH ... ORDER BY ... RETURN ...
101
+ # This is a syntax error in our grammar
102
+ order_by_match = re.search(r'\bORDER\s+BY\b', normalized, re.IGNORECASE)
103
+ return_match = re.search(r'\bRETURN\b', normalized, re.IGNORECASE)
104
+ if order_by_match and return_match and order_by_match.start() < return_match.start():
105
+ # ORDER BY appears before RETURN — swap them
106
+ order_clause = normalized[order_by_match.start():return_match.start()].strip()
107
+ # Extract LIMIT from after ORDER BY if present
108
+ limit_match = re.search(r'\s+LIMIT\s+\d+', order_clause, re.IGNORECASE)
109
+ if limit_match:
110
+ limit_clause = limit_match.group(0)
111
+ order_clause = order_clause[:limit_match.start()] + order_clause[limit_match.end():]
112
+ else:
113
+ limit_clause = ''
114
+ ret_part = normalized[return_match.start():].strip()
115
+ # Remove LIMIT from return part if present
116
+ ret_limit = re.search(r'\s+LIMIT\s+\d+', ret_part, re.IGNORECASE)
117
+ if ret_limit:
118
+ if not limit_clause:
119
+ limit_clause = ret_limit.group(0)
120
+ ret_part = ret_part[:ret_limit.start()] + ret_part[ret_limit.end():]
121
+ before_order = normalized[:order_by_match.start()].strip()
122
+ normalized = before_order + ' ' + ret_part + ' ' + order_clause + ' ' + limit_clause
123
+ normalized = ' '.join(normalized.split()) # collapse whitespace
124
+
125
+ # 12. Replace single-quoted strings with double-quoted (our grammar uses double quotes)
126
+ normalized = normalized.replace("'", '"')
127
+
128
+ return normalized
129
+
130
+
131
+ def classify_query(gql: str) -> list[str]:
132
+ """Classify a GQL query into feature categories."""
133
+ features = []
134
+ upper = gql.upper()
135
+ if "COUNT(" in upper or "SUM(" in upper or "AVG(" in upper or "MIN(" in upper or "MAX(" in upper:
136
+ features.append("aggregation")
137
+ if "ORDER BY" in upper:
138
+ features.append("order_by")
139
+ if "LIMIT" in upper:
140
+ features.append("limit")
141
+ if gql.count("-[") >= 2 or gql.count("]-") >= 2:
142
+ features.append("multi_hop")
143
+ if "WHERE" in upper:
144
+ features.append("filter")
145
+ if re.search(r'\bAND\b', upper) and "WHERE" not in upper:
146
+ features.append("multi_pattern") # comma patterns
147
+ if "*" in gql and ("]-" in gql or "-[" in gql):
148
+ features.append("rpq")
149
+ if "!=" in gql or " NOT " in upper:
150
+ features.append("negation")
151
+ if "," in gql.split("MATCH")[-1].split("RETURN")[0]:
152
+ features.append("multi_pattern")
153
+ if " IS NULL" in upper or " IS NOT NULL" in upper:
154
+ features.append("is_null")
155
+ if not features:
156
+ features.append("simple_lookup")
157
+ return features
158
+
159
+
160
+ def classify_error(exc: Exception) -> str:
161
+ """Classify a parse error into a human-readable reason."""
162
+ msg = str(exc)
163
+ if isinstance(exc, UnexpectedToken):
164
+ token = str(exc.token) if exc.token else ""
165
+ # Extract the unexpected token value
166
+ if "IS" in token and "NULL" in msg:
167
+ return "IS NULL / IS NOT NULL (unsupported)"
168
+ if "DISTINCT" in msg.upper():
169
+ return "DISTINCT (unsupported)"
170
+ if "CASE" in msg.upper() or "WHEN" in msg.upper():
171
+ return "CASE/WHEN (unsupported)"
172
+ if "IN " in token or " IN" in token:
173
+ return "IN operator (unsupported)"
174
+ if "`" in token:
175
+ return f"backtick identifier: {token[:40]}"
176
+ if "(" in token and ")" not in token:
177
+ return f"unexpected token: {token[:40]}"
178
+ if "->" not in msg and "<-" not in msg and "-[" not in msg:
179
+ return f"unexpected token: {token[:60]}"
180
+ return f"unexpected token: {token[:60]}"
181
+ if isinstance(exc, UnexpectedCharacters):
182
+ return f"lexer error: {msg[:80]}"
183
+ if isinstance(exc, UnexpectedEOF):
184
+ return "unexpected EOF"
185
+ return f"other: {type(exc).__name__}: {msg[:80]}"
186
+
187
+
188
+ def evaluate(data_path: str, max_queries: int | None = None):
189
+ """Parse all GQLBench queries against GQL-Core grammar."""
190
+ with open(data_path, "r", encoding="utf-8") as f:
191
+ data = json.load(f)
192
+
193
+ if max_queries:
194
+ data = data[:max_queries]
195
+
196
+ results = {
197
+ "total": len(data),
198
+ "parsed": 0,
199
+ "failed": 0,
200
+ "features": Counter(),
201
+ "passed_features": Counter(),
202
+ "failed_features": Counter(),
203
+ "error_types": Counter(),
204
+ "dialects": Counter(),
205
+ "by_db": Counter(),
206
+ "failures": [],
207
+ }
208
+
209
+ print(f"Evaluating {len(data)} queries from {Path(data_path).name}...")
210
+ for i, entry in enumerate(data):
211
+ gql = entry["gql_statement"]
212
+ dialect = entry.get("gql_dialect", "unknown")
213
+ db_id = entry.get("db_id", "unknown")
214
+ features = classify_query(gql)
215
+ results["dialects"][dialect] += 1
216
+ results["by_db"][db_id] += 1
217
+
218
+ for f in features:
219
+ results["features"][f] += 1
220
+
221
+ try:
222
+ normalized = normalize_gql(gql)
223
+ if normalized is None:
224
+ results["failed"] += 1
225
+ results["error_types"]["unsupported feature (WITH/DISTINCT/COLLECT/etc)"] += 1
226
+ for f in features:
227
+ results["failed_features"][f] += 1
228
+ else:
229
+ gql_parse(normalized)
230
+ results["parsed"] += 1
231
+ for f in features:
232
+ results["passed_features"][f] += 1
233
+ except Exception as exc:
234
+ results["failed"] += 1
235
+ error_cat = classify_error(exc)
236
+ results["error_types"][error_cat] += 1
237
+ for f in features:
238
+ results["failed_features"][f] += 1
239
+ if len(results["failures"]) < 200:
240
+ results["failures"].append({
241
+ "db": db_id,
242
+ "gql": gql[:200],
243
+ "features": features,
244
+ "error": error_cat,
245
+ })
246
+
247
+ if (i + 1) % 5000 == 0:
248
+ pct = 100 * results["parsed"] / (i + 1)
249
+ print(f" {i+1}/{len(data)}: {results['parsed']} parsed ({pct:.1f}%)")
250
+
251
+ pct = 100 * results["parsed"] / results["total"]
252
+ print(f"\n FINAL: {results['parsed']}/{results['total']} parsed ({pct:.1f}%)")
253
+ print(f" {results['failed']} failed")
254
+
255
+ print(f"\n Error breakdown:")
256
+ for reason, count in results["error_types"].most_common(15):
257
+ print(f" {reason}: {count}")
258
+
259
+ print(f"\n Feature coverage (parsed / total):")
260
+ for feat in sorted(results["features"].keys()):
261
+ total = results["features"][feat]
262
+ parsed = results["passed_features"][feat]
263
+ pct_feat = 100 * parsed / total if total else 0
264
+ print(f" {feat:<20s}: {parsed:>5}/{total:<5} ({pct_feat:.0f}%)")
265
+
266
+ return results
267
+
268
+
269
+ if __name__ == "__main__":
270
+ import argparse
271
+
272
+ ap = argparse.ArgumentParser()
273
+ ap.add_argument("--data", default="/tmp/gqlbench/benchmark_data_new/nl_gql/test.json")
274
+ ap.add_argument("--max", type=int, default=None, help="Limit queries for quick testing")
275
+ ap.add_argument("--out", default="benchmark/results/gqlbench_eval.json")
276
+ args = ap.parse_args()
277
+
278
+ results = evaluate(args.data, args.max)
279
+
280
+ out_path = ROOT / args.out
281
+ out_path.parent.mkdir(parents=True, exist_ok=True)
282
+ # Convert Counter to dict for JSON
283
+ out = {k: dict(v) if isinstance(v, Counter) else v for k, v in results.items()}
284
+ out_path.write_text(json.dumps(out, indent=2, default=str))
285
+ print(f"\nWrote {out_path}")
@@ -0,0 +1,191 @@
1
+ """Logical-Reasoning Benchmark (LRB).
2
+
3
+ A second class of queries beyond `benchmark.queries.QUERIES`. Each LR query
4
+ deliberately exercises a *reasoning pattern* the simple lookup queries don't
5
+ — conjunction over shared variables, transitive closure, multi-edge
6
+ constraints, heterogeneous-path composition, and RPQ + numeric filters.
7
+
8
+ Why this matters: the simple Q1–Q5 set verifies that the executor produces
9
+ correct rows for direct relational queries. LRB demonstrates that the engine
10
+ can answer questions that *require* the graph model — questions where SQL
11
+ either needs a `WITH RECURSIVE`, a multi-way self-join, or several `UNION ALL`
12
+ branches to express the same intent.
13
+
14
+ Captain identification is intentionally avoided here. cricsheet does not
15
+ ship a canonical per-match captain field, so the parser's "first-listed
16
+ player" heuristic is unreliable on real data. LRB queries depend only on
17
+ edges whose semantics are unambiguous: BATTED_IN, BOWLED_IN, PLAYED_AT,
18
+ TEAMMATES_WITH, NEXT_DELIVERY.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ LR_QUERIES: list[dict] = [
24
+ {
25
+ "name": "LR1_all_rounders",
26
+ "purpose": (
27
+ "Conjunction over shared variables: players who both batted AND "
28
+ "bowled in the same match. Tests multi-pattern join with two "
29
+ "shared bindings (p, m)."
30
+ ),
31
+ "reasoning_pattern": "conjunctive multi-pattern",
32
+ "cypher": (
33
+ "MATCH (p:Player)-[b:BATTED_IN]->(m:Match), (p)-[w:BOWLED_IN]->(m) "
34
+ "WHERE b.runs > 0 AND w.wickets > 0 "
35
+ "RETURN p.name AS allrounder, COUNT(m) AS matches "
36
+ "ORDER BY matches DESC LIMIT 10"
37
+ ),
38
+ # SQL: self-join batted_in × bowled_in on (player_id, match_id).
39
+ # In SQL this is one INNER JOIN — but the relational schema must
40
+ # already have separate batted_in and bowled_in tables, and the
41
+ # query must explicitly join on both columns. In Cypher the join
42
+ # is implicit from the shared (p, m) variables in two patterns.
43
+ "sql": (
44
+ "SELECT pl.name AS allrounder, COUNT(DISTINCT b.match_id) AS matches "
45
+ "FROM batted_in b "
46
+ "JOIN bowled_in w ON w.player_id = b.player_id AND w.match_id = b.match_id "
47
+ "JOIN players pl ON pl.id = b.player_id "
48
+ "WHERE b.runs > 0 AND w.wickets > 0 "
49
+ "GROUP BY pl.id, pl.name "
50
+ "ORDER BY matches DESC, pl.name ASC LIMIT 10"
51
+ ),
52
+ "key_columns": ("allrounder", "matches"),
53
+ },
54
+ {
55
+ "name": "LR2_teammates_within_two_hops",
56
+ "purpose": (
57
+ "Bounded transitive closure: players reachable from a seed via "
58
+ "1 OR 2 TEAMMATES_WITH hops (undirected). Tests RPQ bounded "
59
+ "Kleene over an undirected edge."
60
+ ),
61
+ "reasoning_pattern": "bounded transitive closure (RPQ)",
62
+ "cypher": (
63
+ "MATCH (p1:Player)-[:TEAMMATES_WITH*1..2]-(p2:Player) "
64
+ 'WHERE p1.name = "Babar Azam" '
65
+ "RETURN p2.name AS within_2_hops "
66
+ "ORDER BY within_2_hops ASC"
67
+ ),
68
+ # SQL: recursive CTE. The CASE expressions are needed because we
69
+ # store TEAMMATES_WITH canonically (player_a_id < player_b_id);
70
+ # for undirected traversal we have to check both columns. Note
71
+ # the explicit depth bound and seed-exclusion to mirror Cypher.
72
+ "sql": (
73
+ "WITH RECURSIVE reach(node, depth) AS ( "
74
+ " SELECT CASE WHEN player_a_id = (SELECT id FROM players WHERE name='Babar Azam') "
75
+ " THEN player_b_id ELSE player_a_id END AS node, 1 AS depth "
76
+ " FROM teammates_with "
77
+ " WHERE player_a_id = (SELECT id FROM players WHERE name='Babar Azam') "
78
+ " OR player_b_id = (SELECT id FROM players WHERE name='Babar Azam') "
79
+ " UNION "
80
+ " SELECT CASE WHEN t.player_a_id = r.node THEN t.player_b_id ELSE t.player_a_id END, "
81
+ " r.depth + 1 "
82
+ " FROM teammates_with t JOIN reach r "
83
+ " ON (t.player_a_id = r.node OR t.player_b_id = r.node) "
84
+ " WHERE r.depth < 2 "
85
+ ") "
86
+ "SELECT DISTINCT pl.name AS within_2_hops "
87
+ "FROM reach r JOIN players pl ON pl.id = r.node "
88
+ "WHERE pl.name != 'Babar Azam' "
89
+ "ORDER BY within_2_hops ASC"
90
+ ),
91
+ "key_columns": ("within_2_hops",),
92
+ },
93
+ {
94
+ "name": "LR3_test_centurions",
95
+ "purpose": (
96
+ "Multi-edge constraint + format filter: players who scored a "
97
+ "century (runs >= 100) in a Test match. Tests numeric threshold "
98
+ "predicates over an edge property combined with a node property."
99
+ ),
100
+ "reasoning_pattern": "multi-edge constraint with threshold",
101
+ "cypher": (
102
+ "MATCH (p:Player)-[r:BATTED_IN]->(m:Match) "
103
+ 'WHERE r.runs >= 100 AND m.format = "Test" '
104
+ "RETURN p.name AS centurion, COUNT(m) AS test_hundreds "
105
+ "ORDER BY test_hundreds DESC, centurion ASC LIMIT 10"
106
+ ),
107
+ "sql": (
108
+ "SELECT pl.name AS centurion, COUNT(*) AS test_hundreds "
109
+ "FROM batted_in b "
110
+ "JOIN players pl ON pl.id = b.player_id "
111
+ "JOIN matches m ON m.id = b.match_id "
112
+ "WHERE b.runs >= 100 AND m.format = 'Test' "
113
+ "GROUP BY pl.id, pl.name "
114
+ "ORDER BY test_hundreds DESC, pl.name ASC LIMIT 10"
115
+ ),
116
+ "key_columns": ("centurion", "test_hundreds"),
117
+ },
118
+ {
119
+ "name": "LR4_co_venue_batters",
120
+ "purpose": (
121
+ "Heterogeneous-path composition: players who have batted at a "
122
+ "venue where Babar Azam also batted. Joins on a shared Venue "
123
+ "node across two independent path patterns. Tests inequality "
124
+ "filter (`!=`) and 4-edge graph composition."
125
+ ),
126
+ "reasoning_pattern": "heterogeneous-path composition (self-join on venue)",
127
+ "cypher": (
128
+ "MATCH (p1:Player)-[:BATTED_IN]->(m1:Match)-[:PLAYED_AT]->(v:Venue), "
129
+ " (p2:Player)-[:BATTED_IN]->(m2:Match)-[:PLAYED_AT]->(v:Venue) "
130
+ 'WHERE p1.name = "Babar Azam" AND p2.name != "Babar Azam" '
131
+ "RETURN p2.name AS co_venue_batter, COUNT(v) AS shared_venue_instances "
132
+ "ORDER BY shared_venue_instances DESC, co_venue_batter ASC LIMIT 10"
133
+ ),
134
+ "sql": (
135
+ "SELECT pl2.name AS co_venue_batter, COUNT(*) AS shared_venue_instances "
136
+ "FROM batted_in b1 "
137
+ "JOIN players pl1 ON pl1.id = b1.player_id "
138
+ "JOIN matches m1 ON m1.id = b1.match_id "
139
+ "JOIN venues v ON v.id = m1.venue_id "
140
+ "JOIN matches m2 ON m2.venue_id = v.id "
141
+ "JOIN batted_in b2 ON b2.match_id = m2.id "
142
+ "JOIN players pl2 ON pl2.id = b2.player_id "
143
+ "WHERE pl1.name = 'Babar Azam' AND pl2.name != 'Babar Azam' "
144
+ "GROUP BY pl2.id, pl2.name "
145
+ "ORDER BY shared_venue_instances DESC, pl2.name ASC LIMIT 10"
146
+ ),
147
+ "key_columns": ("co_venue_batter", "shared_venue_instances"),
148
+ },
149
+ {
150
+ "name": "LR5_scoring_chain_from_first_ball",
151
+ "purpose": (
152
+ "RPQ + numeric filter: from a specific starting delivery, "
153
+ "how many balls within 12 hops scored runs? Tests bounded "
154
+ "Kleene plus a comparison operator (`runs_batter > 0`) on "
155
+ "the target node. {start_id} is resolved at run time."
156
+ ),
157
+ "reasoning_pattern": "RPQ with target-side property filter",
158
+ "cypher": (
159
+ "MATCH (d1:Delivery)-[:NEXT_DELIVERY*1..12]->(d2:Delivery) "
160
+ 'WHERE d1.id = "{start_id}" AND d2.runs_batter > 0 '
161
+ "RETURN COUNT(d2) AS scoring_balls"
162
+ ),
163
+ "sql": (
164
+ "WITH RECURSIVE chain(end_id, depth) AS ( "
165
+ " SELECT next_id, 1 FROM next_delivery WHERE prev_id = '{start_id}' "
166
+ " UNION ALL "
167
+ " SELECT n.next_id, c.depth + 1 "
168
+ " FROM chain c JOIN next_delivery n ON n.prev_id = c.end_id "
169
+ " WHERE c.depth < 12 "
170
+ ") "
171
+ "SELECT COUNT(*) AS scoring_balls "
172
+ "FROM chain c JOIN deliveries d ON d.id = c.end_id "
173
+ "WHERE d.runs_batter > 0"
174
+ ),
175
+ "key_columns": ("scoring_balls",),
176
+ "needs_start_id": True,
177
+ },
178
+ ]
179
+
180
+
181
+ def expressibility(query: dict) -> dict:
182
+ """Same shape as benchmark.queries.expressibility — token count + recursion flag."""
183
+ cypher_tokens = len(query["cypher"].split())
184
+ sql_tokens = len(query["sql"].split())
185
+ return {
186
+ "cypher_tokens": cypher_tokens,
187
+ "sql_tokens": sql_tokens,
188
+ "ratio_sql_over_cypher": round(sql_tokens / cypher_tokens, 2),
189
+ "sql_recursive": "WITH RECURSIVE" in query["sql"].upper(),
190
+ "reasoning_pattern": query["reasoning_pattern"],
191
+ }