codecop 0.1.0__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 (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,77 @@
1
+ """How much a query reads against what it returns: two ratios that say which kind of waste a heavy read is.
2
+
3
+ rows_read_per_row_returned rows read / rows returned. High: the query looks at many rows to keep few
4
+ (a filter the key cannot use, a scan behind a LIMIT).
5
+ bytes_read_per_row_read bytes read / rows read. High: each row is expensive (wide or heavy columns).
6
+
7
+ Bytes read alone hides which of the two it is. Both are per run, from totals over the runs.
8
+
9
+ Reading many rows to return few is the whole point of an aggregate (GROUP BY, count()). `classify` marks
10
+ those from the SQL shape alone, so the first ratio is not read as waste there. The ratios rank and explain;
11
+ nothing here changes a severity.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+
18
+ STRING = re.compile(r"'(?:[^'\\]|\\.|'')*'")
19
+ COMMENT = re.compile(r"/\*.*?\*/|--[^\n]*", re.S)
20
+ AGGREGATE = re.compile(
21
+ r"\b(?:count|sum|avg|min|max|any|anyLast|uniq\w*|argMax|argMin|groupArray\w*|groupUniqArray\w*|quantiles?\w*|median\w*|"
22
+ r"topK\w*|stddev\w*|var(?:Pop|Samp)\w*|corr|covar\w*|sumMap|minMap|maxMap|array_agg|string_agg|json_agg|jsonb_agg|bool_and|bool_or|every|"
23
+ r"count_big|percentile_\w+)(?:If|State|Merge|OrNull|OrDefault|Distinct|Array)*\s*\(\)", re.I)
24
+ COUNT_ONLY = re.compile(r"^\s*count(?:If)?\s*\(\)(?:\s*(?:as\s+)?[\w`\"]+)?\s*$", re.I)
25
+
26
+
27
+ def flatten(sql: str) -> str:
28
+ """The statement at depth 0: every parenthesised group, subqueries and CTE bodies included, reduced to `()`."""
29
+ s = STRING.sub("?", COMMENT.sub(" ", sql or ""))
30
+ prev = None
31
+ while prev != s:
32
+ prev = s
33
+ s = re.sub(r"\([^()]*\)", "\u0001", s)
34
+ return s.replace("\u0001", "()")
35
+
36
+
37
+ def classify(sql: str) -> dict:
38
+ """Is the statement an aggregate by its shape? {"aggregate": bool, "aggregate_kind": "" | count | aggregate | group_by}.
39
+
40
+ Looks at the outermost SELECT only (after any WITH list): a subquery that aggregates does not make the statement
41
+ one. A window function (`... OVER ()`) is not an aggregate: it returns a row per row."""
42
+ flat = flatten(sql)
43
+ m = re.search(r"\bselect\b(.*)", flat, re.I | re.S)
44
+ if not m:
45
+ return {"aggregate": False, "aggregate_kind": ""}
46
+ body = m.group(1)
47
+ select_list = re.split(r"\bfrom\b", body, maxsplit=1, flags=re.I)[0]
48
+ select_list = re.sub(r"^\s*distinct\b", "", select_list, flags=re.I)
49
+ calls = [c for c in AGGREGATE.finditer(select_list) if not re.match(r"\s*over\b", select_list[c.end():], re.I)]
50
+ if re.search(r"\bgroup\s+by\b", body, re.I):
51
+ return {"aggregate": True, "aggregate_kind": "group_by"}
52
+ if calls:
53
+ return {"aggregate": True, "aggregate_kind": "count" if COUNT_ONLY.match(select_list) else "aggregate"}
54
+ return {"aggregate": False, "aggregate_kind": ""}
55
+
56
+
57
+ def ratios(read_rows, read_bytes, result_rows, executions: int = 1, result_bytes=None) -> dict:
58
+ """Per-run volumes and the two ratios. A ratio is None when its denominator is zero or unknown."""
59
+ n = max(int(executions or 0), 1)
60
+ read_rows, read_bytes = int(read_rows or 0), int(read_bytes or 0)
61
+ known_result = result_rows is not None
62
+ result_rows = int(result_rows or 0)
63
+ out = {
64
+ "rows_read_per_run": round(read_rows / n, 1), "bytes_read_per_run": round(read_bytes / n, 1),
65
+ "rows_returned_per_run": round(result_rows / n, 1) if known_result else None,
66
+ "rows_read_per_row_returned": round(read_rows / result_rows, 2) if result_rows else None,
67
+ "bytes_read_per_row_read": round(read_bytes / read_rows, 1) if read_rows else None,
68
+ }
69
+ if result_bytes is not None:
70
+ result_bytes = int(result_bytes or 0)
71
+ out["bytes_returned_per_run"] = round(result_bytes / n, 1)
72
+ out["bytes_read_per_byte_returned"] = round(read_bytes / result_bytes, 2) if result_bytes else None
73
+ return out
74
+
75
+
76
+ RATIO_KEYS = ("rows_read_per_run", "bytes_read_per_run", "rows_returned_per_run", "rows_read_per_row_returned", "bytes_read_per_row_read",
77
+ "bytes_returned_per_run", "bytes_read_per_byte_returned", "aggregate", "aggregate_kind")
@@ -0,0 +1,126 @@
1
+ """Tier D: column statistics by sampling. Reads table data, so it runs only when asked for (`--sample`).
2
+
3
+ What comes back per column: an approximate distinct count, the share of rows held by the ten most
4
+ common values (the share only, never a value), and for date and time columns the oldest and newest
5
+ value. No other column value leaves the database.
6
+
7
+ Statements are built from identifiers the catalog returned, each checked against a strict pattern and
8
+ quoted. The read is capped: ClickHouse stops after `rows` rows (`read_overflow_mode = 'break'`, the
9
+ first rows in key order, so a skewed leading key column skews the sample); Postgres reads a
10
+ block sample sized to about `rows` rows (`TABLESAMPLE SYSTEM`).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+
17
+ from . import SAMPLE_LIMITS, DbError, Limits, Refused, Statement
18
+
19
+ IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
20
+ TIME_TYPE = re.compile(r"^(?:Nullable\()?(?:Date|DateTime)|^(?:date|timestamp)", re.I)
21
+ SKIP_TYPE = re.compile(r"^(?:Array|Map|Tuple|Nested|JSON|Object|AggregateFunction|json|jsonb|bytea|xml|tsvector|.*\[\])", re.I)
22
+ MAX_COLUMNS = 30
23
+ TOP_SHARE_COLUMNS = 6
24
+
25
+
26
+ def _columns(table: dict) -> list[dict]:
27
+ return [c for c in table.get("columns") or [] if IDENT.match(c["name"]) and not SKIP_TYPE.match(c["type"])][:MAX_COLUMNS]
28
+
29
+
30
+ def _check(*names: str) -> None:
31
+ for name in names:
32
+ if not IDENT.match(name or ""):
33
+ raise DbError(f"`{name}` is not a plain identifier: not sampled.")
34
+
35
+
36
+ def clickhouse_statements(table: dict, rows: int) -> list[Statement]:
37
+ """The statements `--sample` would send for one ClickHouse table."""
38
+ _check(table["database"], table["name"])
39
+ cols = _columns(table)
40
+ if not cols:
41
+ return []
42
+ limits = Limits(seconds=SAMPLE_LIMITS.seconds, rows_to_read=rows, bytes_to_read=SAMPLE_LIMITS.bytes_to_read,
43
+ result_rows=SAMPLE_LIMITS.result_rows, memory_bytes=SAMPLE_LIMITS.memory_bytes, threads=SAMPLE_LIMITS.threads)
44
+ target = f"`{table['database']}`.`{table['name']}`"
45
+ parts = ["count() AS sampled_rows"]
46
+ for i, c in enumerate(cols):
47
+ parts.append(f"uniqCombined(12)(`{c['name']}`) AS d{i}")
48
+ if TIME_TYPE.match(c["type"]):
49
+ parts += [f"toString(min(`{c['name']}`)) AS lo{i}", f"toString(max(`{c['name']}`)) AS hi{i}"]
50
+ out = [Statement(f"ch.sample.columns:{table['name']}", "D", f"SELECT {', '.join(parts)} FROM {target}",
51
+ "Approximate distinct counts, and the time range of date columns, over a capped read.", limits)]
52
+ for i, c in enumerate(cols[:TOP_SHARE_COLUMNS * 3]):
53
+ if TIME_TYPE.match(c["type"]) or len(out) > TOP_SHARE_COLUMNS:
54
+ continue
55
+ out.append(Statement(
56
+ f"ch.sample.top_share:{table['name']}.{c['name']}", "D",
57
+ f"SELECT sum(n) AS sampled_rows, count() AS values_seen, arraySum(arraySlice(arrayReverseSort(groupArray(n)), 1, 10)) AS top10_rows "
58
+ f"FROM (SELECT count() AS n FROM {target} GROUP BY `{c['name']}`)",
59
+ "How concentrated a column is: the share of rows in its ten most common values. No value is returned.", limits))
60
+ return out
61
+
62
+
63
+ def postgres_statements(table: dict, rows: int) -> list[Statement]:
64
+ _check(table["schema"], table["name"])
65
+ cols = _columns(table)[:12]
66
+ if not cols:
67
+ return []
68
+ percent = min(100.0, max(0.001, round(100.0 * rows / max(table.get("rows") or 1, 1), 4)))
69
+ target = f"\"{table['schema']}\".\"{table['name']}\" TABLESAMPLE SYSTEM ({percent}) REPEATABLE (1)"
70
+ parts = ["count(*) AS sampled_rows"]
71
+ for i, c in enumerate(cols):
72
+ parts.append(f"count(DISTINCT \"{c['name']}\") AS d{i}")
73
+ if TIME_TYPE.match(c["type"]):
74
+ parts += [f"min(\"{c['name']}\")::text AS lo{i}", f"max(\"{c['name']}\")::text AS hi{i}"]
75
+ return [Statement(f"pg.sample.columns:{table['name']}", "D", f"SELECT {', '.join(parts)} FROM {target}",
76
+ "Distinct counts, and the time range of date columns, over a block sample.", SAMPLE_LIMITS)]
77
+
78
+
79
+ def statements(engine: str, table: dict, rows: int) -> list[Statement]:
80
+ return clickhouse_statements(table, rows) if engine == "clickhouse" else postgres_statements(table, rows)
81
+
82
+
83
+ def run(reader, catalog: dict, *, tables: list[str] | None = None, rows: int = 1_000_000, max_tables: int = 10) -> dict:
84
+ """Sample the named tables (or the largest ones). Returns per-column statistics; raises nothing for one refused table."""
85
+ wanted = {t.split(".")[-1] for t in tables or []}
86
+ chosen = [t for t in catalog.get("tables") or [] if (not wanted or t["name"] in wanted) and t.get("columns")
87
+ and (t.get("engine") == "postgres" or "MergeTree" in t.get("engine", ""))]
88
+ chosen = sorted(chosen, key=lambda t: -(t.get("rows") or 0))[:max_tables]
89
+ out = []
90
+ for table in chosen:
91
+ try:
92
+ stmts = statements(reader.engine, table, rows)
93
+ except DbError as e:
94
+ out.append({"table": table["name"], "ok": False, "error": str(e)})
95
+ continue
96
+ cols = _columns(table) if reader.engine == "clickhouse" else _columns(table)[:12]
97
+ entry = {"table": table["name"], "ok": True, "sampled_rows": 0, "table_rows": table.get("rows") or 0, "columns": {},
98
+ "basis": "first rows in key order" if reader.engine == "clickhouse" else "block sample"}
99
+ for stmt in stmts:
100
+ try:
101
+ if reader.engine == "clickhouse":
102
+ reader.extra_settings = {"read_overflow_mode": "break"}
103
+ rows_back = reader.run_statement(stmt, {})
104
+ except Refused as e:
105
+ entry.setdefault("refused", []).append(str(e)[:160])
106
+ continue
107
+ finally:
108
+ if reader.engine == "clickhouse":
109
+ reader.extra_settings = {}
110
+ if not rows_back:
111
+ continue
112
+ r = rows_back[0]
113
+ if ".columns:" in stmt.id:
114
+ entry["sampled_rows"] = int(r["sampled_rows"] or 0)
115
+ for i, c in enumerate(cols):
116
+ if f"d{i}" in r:
117
+ col = entry["columns"].setdefault(c["name"], {})
118
+ col["distinct_in_sample"] = int(r[f"d{i}"] or 0)
119
+ if f"lo{i}" in r:
120
+ col["min"], col["max"] = r[f"lo{i}"], r[f"hi{i}"]
121
+ else:
122
+ name = stmt.id.rsplit(".", 1)[-1]
123
+ total = int(r["sampled_rows"] or 0)
124
+ entry["columns"].setdefault(name, {})["top10_share"] = round(int(r["top10_rows"] or 0) / total, 4) if total else None
125
+ out.append(entry)
126
+ return {"engine": reader.engine, "rows_cap": rows, "tables": out}
codecop/relations.py ADDED
@@ -0,0 +1,227 @@
1
+ """Invariants between tables that the generated data keeps: foreign keys, and columns a row shares with its parent.
2
+
3
+ Columns are generated one by one, so without this a feed's category belongs to another user and a child's tenant is
4
+ not its parent's. An application never writes such rows, and a rewrite that is correct for every row the application
5
+ can write (`AND feeds.user_id = c.user_id`) returns different results on them: the equivalence check then rejects a
6
+ correct fix.
7
+
8
+ A relation is
9
+
10
+ {table, column, parent, parent_column, same_as_parent: [{column, parent_column}], source, basis}
11
+
12
+ `table.column` points at an existing row of `parent` (its `parent_column`), and every column in `same_as_parent` has
13
+ the value that parent row has ("a feed's user_id is its category's user_id"). Relations come from two places:
14
+
15
+ declared foreign keys in the table definitions (PostgreSQL: REFERENCES, FOREIGN KEY, ALTER TABLE ... ADD FOREIGN KEY).
16
+ A composite key (tenant_id, id) -> (tenant_id, id) becomes one relation on the identifying column with the
17
+ other columns as `same_as_parent`.
18
+ profile `relations` on a profile table: what the agent read from joins, names and the code that writes the rows.
19
+ This is the only source of `same_as_parent` for a single-column key, and the only source on ClickHouse.
20
+ The developer can edit them in profile.json like every other number.
21
+
22
+ How the sandbox realises one (engines/postgres.py, engines/clickhouse.py), per generated child row:
23
+
24
+ 1. the row's own generated values are kept when they already agree: the key names an existing parent row and the
25
+ shared columns have that row's values;
26
+ 2. otherwise a parent row is chosen among those whose shared column has the child's value (so a pinned tenant keeps
27
+ its share of the child's rows), by a hash of the row number;
28
+ 3. when no parent has that value, the child takes the shared values of the parent its key names, or of a parent
29
+ chosen by the hash of the row number.
30
+
31
+ So the invariant always wins over an independently generated value, and the choice depends only on the row number and
32
+ the loaded parent: the same profile gives the same data. Parents are loaded before their children. What could not be
33
+ enforced (a parent that failed to build, a cycle, a table that refers to itself) is recorded with the reason, and
34
+ after each load the sandbox counts the rows that break each relation and records the count.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ from . import engines
40
+
41
+ DECLARED = "declared foreign key"
42
+ PROFILE = "data profile"
43
+
44
+
45
+ def _key(name: str) -> str:
46
+ return name.replace('"', "").replace("`", "").lower()
47
+
48
+
49
+ def table_columns(definition: dict, engine: str) -> tuple[list[str], list[str]]:
50
+ """(columns, primary key columns) of a definition, as written. Empty when the definition can not be read."""
51
+ sql = definition.get("create_sql") or ""
52
+ if engine == "postgres":
53
+ from .engines.pg_ddl import parse_definition
54
+ t = parse_definition(sql, definition["name"])
55
+ return list(t.columns), next(([c.column for c in ix.columns] for ix in t.indexes if ix.primary), [])
56
+ from .rank import _columns
57
+ cols = _columns(sql, definition.get("name") or "")
58
+ return (list(cols[1]) if cols else []), []
59
+
60
+
61
+ def declared(definitions: list[dict], engine: str) -> list[dict]:
62
+ """Relations from the foreign keys the definitions declare. ClickHouse has none."""
63
+ if engine != "postgres":
64
+ return []
65
+ from .engines.pg_ddl import foreign_keys
66
+ eng = engines.get(engine)
67
+ by_key = {_key(eng.canonical_table(d["name"])): d for d in definitions}
68
+ shape = {k: table_columns(d, engine) for k, d in by_key.items()}
69
+ out, seen = [], set()
70
+ for d in definitions:
71
+ for fk in foreign_keys(d.get("create_sql") or ""):
72
+ child = by_key.get(_key(eng.canonical_table(fk["table"])))
73
+ parent = by_key.get(_key(eng.canonical_table(fk["parent"])))
74
+ if child is None or parent is None:
75
+ continue # the parent is not a sandbox table: nothing to agree with
76
+ pcols = fk["parent_columns"] or shape[_key(eng.canonical_table(parent["name"]))][1]
77
+ if len(pcols) != len(fk["columns"]) or not pcols:
78
+ continue
79
+ pairs = list(zip(fk["columns"], pcols))
80
+ pk = shape[_key(eng.canonical_table(parent["name"]))][1]
81
+ # the identifying column of a composite key: the parent's own id rather than the tenant it repeats
82
+ lead = max(pairs, key=lambda cp: (cp[1] in pk and len(pk) == 1, cp[1].lower() == "id", cp[1].lower().endswith("id")
83
+ and not cp[1].lower().startswith(("tenant", "org", "account", "workspace", "project")),
84
+ pairs.index(cp)))
85
+ mark = (child["name"], lead[0], parent["name"], lead[1])
86
+ if mark in seen:
87
+ continue
88
+ seen.add(mark)
89
+ out.append({"table": child["name"], "column": lead[0], "parent": parent["name"], "parent_column": lead[1],
90
+ "same_as_parent": [{"column": c, "parent_column": p} for c, p in pairs if (c, p) != lead],
91
+ "source": DECLARED, "basis": "FOREIGN KEY in the table definition"})
92
+ return out
93
+
94
+
95
+ def stated(profile: dict | None) -> list[dict]:
96
+ """Relations the profile states (the agent's, or the developer's edit)."""
97
+ out = []
98
+ for t in (profile or {}).get("tables") or []:
99
+ for r in t.get("relations") or []:
100
+ if not (r.get("column") and r.get("parent_table") and r.get("parent_column")):
101
+ continue
102
+ out.append({"table": t["name"], "column": r["column"], "parent": r["parent_table"], "parent_column": r["parent_column"],
103
+ "same_as_parent": [{"column": s["column"], "parent_column": s["parent_column"]}
104
+ for s in r.get("same_as_parent") or [] if s.get("column") and s.get("parent_column")],
105
+ "source": PROFILE, "basis": r.get("basis") or ""})
106
+ return out
107
+
108
+
109
+ def resolve(rank: dict, profile: dict | None) -> dict:
110
+ """Every relation between the sandbox's tables, checked against the definitions, and the order to load tables in.
111
+
112
+ Returns {relations, skipped, order}: `relations` are the ones the sandbox enforces, each with its tables under the
113
+ names the definitions use; `skipped` are relations that can not be enforced, each with `reason`; `order` is every
114
+ definition name, parents before children."""
115
+ engine = rank["engine"]
116
+ eng = engines.get(engine)
117
+ definitions = rank.get("table_definitions") or []
118
+ by_key = {_key(eng.canonical_table(d["name"])): d for d in definitions}
119
+ shape = {k: table_columns(d, engine)[0] for k, d in by_key.items()}
120
+
121
+ def column(table_key: str, name: str) -> str | None:
122
+ cols = shape.get(table_key) or []
123
+ return next((c for c in cols if c == name), None) or next((c for c in cols if c.lower() == name.lower()), None)
124
+
125
+ merged: dict[tuple, dict] = {}
126
+ skipped: list[dict] = []
127
+ for r in declared(definitions, engine) + stated(profile):
128
+ ck, pk = _key(eng.canonical_table(r["table"])), _key(eng.canonical_table(r["parent"]))
129
+ if ck not in by_key or pk not in by_key:
130
+ skipped.append({**r, "reason": f"table {r['parent'] if ck in by_key else r['table']} is not one of the sandbox's tables"})
131
+ continue
132
+ col, pcol = column(ck, r["column"]), column(pk, r["parent_column"])
133
+ if shape[ck] and shape[pk] and (col is None or pcol is None):
134
+ skipped.append({**r, "reason": f"column {r['column'] if col is None else r['parent_column']} is not in the table definition"})
135
+ continue
136
+ same = []
137
+ for s in r["same_as_parent"]:
138
+ a, b = column(ck, s["column"]), column(pk, s["parent_column"])
139
+ if (a and b) or not (shape[ck] and shape[pk]):
140
+ same.append({"column": a or s["column"], "parent_column": b or s["parent_column"]})
141
+ rel = {**r, "table": by_key[ck]["name"], "parent": by_key[pk]["name"], "column": col or r["column"],
142
+ "parent_column": pcol or r["parent_column"], "same_as_parent": same}
143
+ if ck == pk:
144
+ skipped.append({**rel, "reason": "the table refers to itself: rows are generated in one pass, so a row's parent is not known yet"})
145
+ continue
146
+ mark = (ck, rel["column"].lower(), pk, rel["parent_column"].lower())
147
+ if mark in merged:
148
+ have = merged[mark]
149
+ names = {s["column"] for s in have["same_as_parent"]}
150
+ have["same_as_parent"] += [s for s in same if s["column"] not in names]
151
+ if rel["source"] not in have["source"]:
152
+ have["source"] += " + " + rel["source"]
153
+ have["basis"] = "; ".join(x for x in (have["basis"], rel["basis"]) if x)
154
+ else:
155
+ merged[mark] = rel
156
+ # one column can follow one parent only; the first relation on a column wins (declared before stated)
157
+ relations, taken = [], set()
158
+ for mark, rel in merged.items():
159
+ if (mark[0], mark[1]) in taken:
160
+ skipped.append({**rel, "reason": f"{rel['column']} already follows another parent"})
161
+ continue
162
+ taken.add((mark[0], mark[1]))
163
+ relations.append(rel)
164
+
165
+ # parents before children; a relation that would close a cycle is not enforced
166
+ order, placed, kept = [], set(), []
167
+ parents: dict[str, set[str]] = {}
168
+ for rel in relations:
169
+ child, parent = rel["table"], rel["parent"]
170
+ if _reaches(parents, parent, child):
171
+ skipped.append({**rel, "reason": f"{parent} already depends on {child}: the cycle is cut here"})
172
+ continue
173
+ parents.setdefault(child, set()).add(parent)
174
+ kept.append(rel)
175
+
176
+ def place(name: str) -> None:
177
+ if name in placed:
178
+ return
179
+ placed.add(name)
180
+ for p in sorted(parents.get(name, ())):
181
+ place(p)
182
+ order.append(name)
183
+
184
+ for d in definitions:
185
+ place(d["name"])
186
+ return {"relations": kept, "skipped": skipped, "order": order}
187
+
188
+
189
+ def _reaches(parents: dict[str, set[str]], start: str, target: str) -> bool:
190
+ stack, seen = [start], set()
191
+ while stack:
192
+ cur = stack.pop()
193
+ if cur == target:
194
+ return True
195
+ if cur in seen:
196
+ continue
197
+ seen.add(cur)
198
+ stack.extend(parents.get(cur, ()))
199
+ return False
200
+
201
+
202
+ def descendants(relations: list[dict], names: set[str]) -> set[str]:
203
+ """`names` and every table that follows one of them: reloading a parent means reloading its children."""
204
+ out = set(names)
205
+ changed = True
206
+ while changed:
207
+ changed = False
208
+ for r in relations:
209
+ if r["parent"] in out and r["table"] not in out:
210
+ out.add(r["table"])
211
+ changed = True
212
+ return out
213
+
214
+
215
+ def row_order(rels: list[dict]) -> list[dict]:
216
+ """The order to apply one table's relations in: a relation whose key column is a shared column of another comes
217
+ first (entries.user_id -> users, then entries.feed_id -> feeds, which shares user_id)."""
218
+ def provides(r: dict) -> bool:
219
+ return any(r["column"] in {s["column"] for s in o["same_as_parent"]} for o in rels if o is not r)
220
+ return sorted(rels, key=lambda r: not provides(r)) # stable: otherwise the order they were given in
221
+
222
+
223
+ def describe(rel: dict) -> str:
224
+ text = f"{rel['table']}.{rel['column']} is a row of {rel['parent']} ({rel['parent_column']})"
225
+ if rel.get("same_as_parent"):
226
+ text += "; " + ", ".join(f"{s['column']} is that row's {s['parent_column']}" for s in rel["same_as_parent"])
227
+ return text