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,385 @@
1
+ {
2
+ "type": "object",
3
+ "required": [
4
+ "candidates",
5
+ "table_definitions",
6
+ "rejected"
7
+ ],
8
+ "additionalProperties": false,
9
+ "properties": {
10
+ "candidates": {
11
+ "type": "array",
12
+ "items": {
13
+ "type": "object",
14
+ "required": [
15
+ "id",
16
+ "title",
17
+ "severity",
18
+ "confidence",
19
+ "baseline_sql",
20
+ "params",
21
+ "tables",
22
+ "variants",
23
+ "origin",
24
+ "causes",
25
+ "assumptions"
26
+ ],
27
+ "additionalProperties": false,
28
+ "properties": {
29
+ "id": {
30
+ "type": "string"
31
+ },
32
+ "title": {
33
+ "type": "string"
34
+ },
35
+ "severity": {
36
+ "type": "string",
37
+ "enum": [
38
+ "high",
39
+ "medium",
40
+ "low"
41
+ ]
42
+ },
43
+ "confidence": {
44
+ "type": "string",
45
+ "enum": [
46
+ "high",
47
+ "medium",
48
+ "low"
49
+ ]
50
+ },
51
+ "baseline_sql": {
52
+ "type": "string"
53
+ },
54
+ "params": {
55
+ "type": "array",
56
+ "items": {
57
+ "type": "object",
58
+ "required": [
59
+ "name",
60
+ "value"
61
+ ],
62
+ "additionalProperties": false,
63
+ "properties": {
64
+ "name": {
65
+ "type": "string"
66
+ },
67
+ "value": {
68
+ "type": "string"
69
+ }
70
+ }
71
+ }
72
+ },
73
+ "tables": {
74
+ "type": "array",
75
+ "items": {
76
+ "type": "string"
77
+ }
78
+ },
79
+ "variants": {
80
+ "type": "array",
81
+ "items": {
82
+ "type": "object",
83
+ "required": [
84
+ "kind",
85
+ "sql",
86
+ "setup_sql",
87
+ "same_results",
88
+ "change",
89
+ "tradeoffs"
90
+ ],
91
+ "additionalProperties": false,
92
+ "properties": {
93
+ "kind": {
94
+ "type": "string",
95
+ "enum": [
96
+ "rewrite",
97
+ "skip_index",
98
+ "projection",
99
+ "ordering_key",
100
+ "materialized_view",
101
+ "column_type",
102
+ "index",
103
+ "partitioning"
104
+ ]
105
+ },
106
+ "sql": {
107
+ "type": "string"
108
+ },
109
+ "setup_sql": {
110
+ "type": "array",
111
+ "items": {
112
+ "type": "string"
113
+ }
114
+ },
115
+ "same_results": {
116
+ "type": "boolean"
117
+ },
118
+ "change": {
119
+ "type": "string"
120
+ },
121
+ "tradeoffs": {
122
+ "type": "array",
123
+ "items": {
124
+ "type": "string",
125
+ "enum": [
126
+ "extra_storage",
127
+ "slower_inserts",
128
+ "backfill",
129
+ "code_change",
130
+ "schema_migration",
131
+ "changes_results",
132
+ "needs_setting"
133
+ ]
134
+ }
135
+ }
136
+ }
137
+ }
138
+ },
139
+ "origin": {
140
+ "type": "object",
141
+ "required": [
142
+ "role",
143
+ "kind",
144
+ "entry_points",
145
+ "frequency",
146
+ "path"
147
+ ],
148
+ "additionalProperties": false,
149
+ "properties": {
150
+ "role": {
151
+ "type": "string",
152
+ "enum": [
153
+ "app",
154
+ "job",
155
+ "script",
156
+ "migration",
157
+ "tooling",
158
+ "test",
159
+ "unknown"
160
+ ]
161
+ },
162
+ "kind": {
163
+ "type": "string",
164
+ "enum": [
165
+ "http",
166
+ "workflow",
167
+ "activity",
168
+ "job",
169
+ "consumer",
170
+ "cli",
171
+ "main",
172
+ "test",
173
+ "unknown"
174
+ ]
175
+ },
176
+ "entry_points": {
177
+ "type": "array",
178
+ "items": {
179
+ "type": "object",
180
+ "required": [
181
+ "kind",
182
+ "name",
183
+ "file",
184
+ "line"
185
+ ],
186
+ "additionalProperties": false,
187
+ "properties": {
188
+ "kind": {
189
+ "type": "string"
190
+ },
191
+ "name": {
192
+ "type": "string"
193
+ },
194
+ "file": {
195
+ "type": "string"
196
+ },
197
+ "line": {
198
+ "type": "integer"
199
+ }
200
+ }
201
+ }
202
+ },
203
+ "frequency": {
204
+ "type": "object",
205
+ "required": [
206
+ "trigger",
207
+ "every_seconds",
208
+ "in_loop",
209
+ "cache_seconds",
210
+ "note"
211
+ ],
212
+ "additionalProperties": false,
213
+ "properties": {
214
+ "trigger": {
215
+ "type": "string",
216
+ "enum": [
217
+ "per_request",
218
+ "per_item",
219
+ "scheduled",
220
+ "on_event",
221
+ "startup",
222
+ "manual",
223
+ "unknown"
224
+ ]
225
+ },
226
+ "every_seconds": {
227
+ "type": "integer"
228
+ },
229
+ "in_loop": {
230
+ "type": "boolean"
231
+ },
232
+ "cache_seconds": {
233
+ "type": "integer"
234
+ },
235
+ "note": {
236
+ "type": "string"
237
+ }
238
+ }
239
+ },
240
+ "path": {
241
+ "type": "array",
242
+ "items": {
243
+ "type": "object",
244
+ "required": [
245
+ "symbol",
246
+ "file",
247
+ "line"
248
+ ],
249
+ "additionalProperties": false,
250
+ "properties": {
251
+ "symbol": {
252
+ "type": "string"
253
+ },
254
+ "file": {
255
+ "type": "string"
256
+ },
257
+ "line": {
258
+ "type": "integer"
259
+ }
260
+ }
261
+ }
262
+ }
263
+ }
264
+ },
265
+ "causes": {
266
+ "type": "array",
267
+ "items": {
268
+ "type": "object",
269
+ "required": [
270
+ "code",
271
+ "column",
272
+ "detail"
273
+ ],
274
+ "additionalProperties": false,
275
+ "properties": {
276
+ "code": {
277
+ "type": "string",
278
+ "enum": [
279
+ "key_not_used",
280
+ "no_partition_pruning",
281
+ "final_merge",
282
+ "wide_read",
283
+ "heavy_columns",
284
+ "per_row_function",
285
+ "full_sort",
286
+ "offset_paging",
287
+ "leading_wildcard",
288
+ "in_loop",
289
+ "unbounded_result",
290
+ "repeated_read",
291
+ "join_order",
292
+ "skip_index_ineffective",
293
+ "cross_tenant_scan",
294
+ "seq_scan",
295
+ "non_sargable",
296
+ "missing_join_index",
297
+ "partial_index_match",
298
+ "not_covering",
299
+ "or_conditions",
300
+ "count_scan",
301
+ "correlated_subquery",
302
+ "no_gin_index",
303
+ "other"
304
+ ]
305
+ },
306
+ "column": {
307
+ "type": "string"
308
+ },
309
+ "detail": {
310
+ "type": "string"
311
+ }
312
+ }
313
+ }
314
+ },
315
+ "assumptions": {
316
+ "type": "array",
317
+ "items": {
318
+ "type": "string"
319
+ }
320
+ }
321
+ }
322
+ }
323
+ },
324
+ "table_definitions": {
325
+ "type": "array",
326
+ "items": {
327
+ "type": "object",
328
+ "required": [
329
+ "name",
330
+ "create_sql",
331
+ "inferred",
332
+ "basis"
333
+ ],
334
+ "additionalProperties": false,
335
+ "properties": {
336
+ "name": {
337
+ "type": "string"
338
+ },
339
+ "create_sql": {
340
+ "type": "string"
341
+ },
342
+ "inferred": {
343
+ "type": "boolean"
344
+ },
345
+ "basis": {
346
+ "type": "string"
347
+ }
348
+ }
349
+ }
350
+ },
351
+ "rejected": {
352
+ "type": "array",
353
+ "items": {
354
+ "type": "object",
355
+ "required": [
356
+ "id",
357
+ "code",
358
+ "detail"
359
+ ],
360
+ "additionalProperties": false,
361
+ "properties": {
362
+ "id": {
363
+ "type": "string"
364
+ },
365
+ "code": {
366
+ "type": "string",
367
+ "enum": [
368
+ "small_table",
369
+ "already_cheap",
370
+ "duplicate",
371
+ "one_off",
372
+ "unresolved_sql",
373
+ "other_engine",
374
+ "cached",
375
+ "other"
376
+ ]
377
+ },
378
+ "detail": {
379
+ "type": "string"
380
+ }
381
+ }
382
+ }
383
+ }
384
+ }
385
+ }
codecop/sizes.py ADDED
@@ -0,0 +1,200 @@
1
+ """How big a column's values are, and what they are made of.
2
+
3
+ A profile column may say, beside its generator kind:
4
+
5
+ content what the value is: one of CONTENT_KINDS (a uuid, an email, a JSON tool call, a model response, ...)
6
+ typical_bytes the size of an ordinary value (the median)
7
+ large_bytes the size of a large value (about the 99th percentile)
8
+ mean_bytes the mean size. Set from the real catalog when one was read; otherwise derived.
9
+ compress_ratio uncompressed / compressed, from the real catalog when one was read
10
+ size_basis, size_confidence, size_evidence where the sizes came from ("agent estimate", "real catalog",
11
+ "real catalog, per partition", "fitted to real workload")
12
+ width_by_age the mean size by the age of the row, from the real catalog's partitions (see below)
13
+
14
+ Sizes follow a log-normal distribution: most values near `typical_bytes`, a long tail up to `large_bytes` and a little
15
+ beyond. That is what payload columns look like in practice, and the tail is what makes a mean several times the median.
16
+ Both data generators (datagen.py, datagen_postgres.py) and the sandbox's disk estimate read the model from here.
17
+
18
+ Why it matters beyond bytes read: ClickHouse cuts a granule at 8,192 rows or 10 MB of uncompressed data, whichever
19
+ comes first. A table of 40 kB rows has granules of about 250 rows, so a key lookup reads hundreds of rows where the same
20
+ lookup on narrow generated rows reads 8,192 per granule.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import math
26
+ from datetime import date
27
+
28
+ CONTENT_KINDS = ("id", "uuid", "hash", "email", "url", "name", "enum", "json", "tool_call", "llm_messages", "llm_response", "text",
29
+ "html", "code", "base64", "ciphertext", "user_agent", "ip", "path", "other")
30
+ JSONISH = ("json", "tool_call")
31
+ MESSAGES = ("llm_messages", "llm_response")
32
+ INCOMPRESSIBLE = ("base64", "ciphertext", "hash")
33
+ PAYLOADS = JSONISH + MESSAGES + ("text", "html", "code", "base64", "ciphertext")
34
+ # uncompressed / compressed, when nothing was measured: what such content does under LZ4 or ZSTD(1) in practice
35
+ DEFAULT_RATIO = {"json": 4.0, "tool_call": 4.0, "llm_messages": 3.5, "llm_response": 3.5, "text": 3.0, "html": 5.0, "code": 4.0,
36
+ "base64": 1.3, "ciphertext": 1.1, "hash": 1.5}
37
+ Z_CAP = 3.0 # the tail is cut at three standard deviations, so one value can not be gigabytes
38
+ P99_Z = 2.326
39
+ MAX_SIGMA = 2.0
40
+ DEFAULT_SIGMA = 1.0 # a payload column with only a mean: a large value is about ten times an ordinary one
41
+ MAX_VALUE_BYTES = 8_000_000
42
+ SIZE_FIELDS = ("content", "typical_bytes", "large_bytes", "mean_bytes", "compress_ratio", "size_basis", "size_confidence", "size_evidence",
43
+ "size_estimate", "width_by_age")
44
+
45
+
46
+ def _capped_mean_factor(sigma: float) -> float:
47
+ """E[exp(sigma * min(Z, Z_CAP))] for a standard normal Z: the mean of the capped log-normal over its median."""
48
+ if sigma <= 0:
49
+ return 1.0
50
+ steps, lo = 2000, -8.0
51
+ width = (Z_CAP - lo) / steps
52
+ total = 0.0
53
+ for i in range(steps):
54
+ z = lo + (i + 0.5) * width
55
+ total += math.exp(sigma * z - z * z / 2) * width
56
+ total /= math.sqrt(2 * math.pi)
57
+ tail = 0.5 * math.erfc(Z_CAP / math.sqrt(2))
58
+ return total + tail * math.exp(sigma * Z_CAP)
59
+
60
+
61
+ def size_model(col: dict) -> dict | None:
62
+ """{median, sigma, mean} in bytes for a column that states a size, else None (the generator's own default applies).
63
+
64
+ A real mean (`mean_bytes`) wins: the spread still comes from the agent's typical and large sizes when it gave both,
65
+ and the median is moved so that the mean is the measured one."""
66
+ typical, large, mean = (float(col.get(k) or 0) for k in ("typical_bytes", "large_bytes", "mean_bytes"))
67
+ if typical <= 0 and mean <= 0:
68
+ return None
69
+ nulls = min(max(float(col.get("null_fraction") or 0), 0.0), 0.95)
70
+ mean /= 1 - nulls # a measured mean is over all rows; the rows that hold a value are that much larger
71
+ if typical > 0 and large > typical:
72
+ sigma = min(math.log(large / typical) / P99_Z, MAX_SIGMA)
73
+ elif typical > 0 and mean <= 0:
74
+ sigma = 0.0
75
+ else:
76
+ sigma = DEFAULT_SIGMA if col.get("content") in PAYLOADS or mean >= 200 else 0.3
77
+ factor = _capped_mean_factor(sigma)
78
+ if mean > 0:
79
+ median = mean / factor
80
+ else:
81
+ median, mean = typical, typical * factor
82
+ return {"median": max(median, 1.0), "sigma": sigma, "mean": max(mean, 1.0)}
83
+
84
+
85
+ def mean_bytes(col: dict) -> float | None:
86
+ """The column's mean size over all rows, NULL rows included (what a catalog reports and what a disk estimate needs)."""
87
+ m = size_model(col)
88
+ if not m:
89
+ return None
90
+ return m["mean"] * (1 - min(max(float(col.get("null_fraction") or 0), 0.0), 0.95))
91
+
92
+
93
+ def compress_ratio(col: dict) -> float:
94
+ if col.get("compress_ratio"):
95
+ return max(float(col["compress_ratio"]), 1.0)
96
+ return DEFAULT_RATIO.get(col.get("content") or "", 3.0 if col.get("content") else 1.2)
97
+
98
+
99
+ # ---- sizes that change with the age of a row --------------------------------
100
+ # A table average hides that recent rows are often heavier (or lighter) than old ones: payloads grow with a product.
101
+ # The real catalog gives each column's bytes per partition; when the partitions are periods of time, a column may say
102
+ #
103
+ # width_by_age {unit, column, bands: [{up_to, mean_bytes, rows, partitions}]}
104
+ #
105
+ # `unit` is the partition's period (day, week, month, year), `column` the time column the table is partitioned on, and
106
+ # a band holds the rows whose time is at most `up_to` periods before now (0 = the current period; null = everything
107
+ # older). The generator then writes each band's rows at that band's mean instead of the table's (datagen.age_scale).
108
+ AGE_UNITS = ("day", "week", "month", "year")
109
+ WIDTH_BANDS = 12 # bands a column may have (setting width_bands under [profile]); the oldest takes the rest
110
+ BAND_TOLERANCE = 1.25 # neighbouring partitions whose widths are within this factor share a band (width_band_tolerance)
111
+ BAND_MATTERS = 1.2 # a column gets bands only when one of them is this far from the column's mean
112
+ REAL_PARTITIONS = "real catalog, per partition"
113
+
114
+
115
+ def partition_day(partition_id: str) -> date | None:
116
+ """The first day of the period a partition id names: 2026, 202611, 20261127. None for an id that is not a period of
117
+ time (a hash, a tenant). A tuple's id (`202611-3`) is read by its first part."""
118
+ head = str(partition_id or "").split("-")[0]
119
+ if not head.isdigit() or len(head) not in (4, 6, 8):
120
+ return None
121
+ year, month, day = int(head[:4]), int(head[4:6] or 1), int(head[6:8] or 1)
122
+ if not 1971 <= year <= 2100:
123
+ return None
124
+ try:
125
+ return date(year, month, day)
126
+ except ValueError:
127
+ return None
128
+
129
+
130
+ def partition_unit(partition_ids: list[str]) -> str | None:
131
+ """The period the partitions of a table are: by the form of their ids, and for full dates by the gaps between them.
132
+ None when any id is not a period of time."""
133
+ heads = [str(p).split("-")[0] for p in partition_ids]
134
+ if not heads or any(partition_day(h) is None for h in heads) or len({len(h) for h in heads}) != 1:
135
+ return None
136
+ if len(heads[0]) != 8:
137
+ return "year" if len(heads[0]) == 4 else "month"
138
+ days = sorted({partition_day(h) for h in heads})
139
+ gaps = [(b - a).days for a, b in zip(days, days[1:])]
140
+ if gaps and min(gaps) >= 28 and all(d.day == 1 for d in days):
141
+ return "month"
142
+ if gaps and min(gaps) >= 7 and all(g % 7 == 0 for g in gaps):
143
+ return "week"
144
+ return "day"
145
+
146
+
147
+ def periods_back(unit: str, newest: date, day: date) -> int:
148
+ """How many periods `day` is before `newest` (0 = the same period)."""
149
+ if unit == "year":
150
+ n = newest.year - day.year
151
+ elif unit == "month":
152
+ n = (newest.year - day.year) * 12 + newest.month - day.month
153
+ else:
154
+ n = (newest - day).days // (7 if unit == "week" else 1)
155
+ return max(n, 0)
156
+
157
+
158
+ def age_bands(points: list[tuple[int, int, int]], max_bands: int = WIDTH_BANDS, tolerance: float = BAND_TOLERANCE) -> list[dict]:
159
+ """Bands of similar width, newest first, from (periods back, rows, uncompressed bytes) per partition.
160
+
161
+ Neighbouring partitions join a band while their width stays within `tolerance` of the band's; the last allowed band
162
+ takes everything older. Partitions that report no size are not in `points`: their rows fall in the band of their age."""
163
+ bands: list[dict] = []
164
+ for back, rows, size in sorted(p for p in points if p[1] > 0 and p[2] > 0):
165
+ width = size / rows
166
+ last = bands[-1] if bands else None
167
+ if last is not None and (len(bands) >= max(max_bands, 1)
168
+ or max(width, last["bytes"] / last["rows"]) <= tolerance * min(width, last["bytes"] / last["rows"])):
169
+ last.update(up_to=back, rows=last["rows"] + rows, bytes=last["bytes"] + size, partitions=last["partitions"] + 1)
170
+ else:
171
+ bands.append({"up_to": back, "rows": rows, "bytes": size, "partitions": 1})
172
+ out = [{"up_to": b["up_to"], "mean_bytes": round(b["bytes"] / b["rows"], 1), "rows": b["rows"], "partitions": b["partitions"]} for b in bands]
173
+ if out:
174
+ out[-1]["up_to"] = None
175
+ return out
176
+
177
+
178
+ def bands_matter(bands: list[dict], mean: float) -> bool:
179
+ """Whether writing these bands would differ from writing the column's mean everywhere."""
180
+ return bool(mean) and len(bands) > 1 and any(
181
+ max(b["mean_bytes"], mean) > BAND_MATTERS * min(b["mean_bytes"], mean) for b in bands)
182
+
183
+
184
+ def age_factors(col: dict) -> list[tuple[int | None, float]]:
185
+ """(up_to, factor) per band: the band's mean over the column's mean. Empty when the column has no usable bands."""
186
+ by_age = col.get("width_by_age") or {}
187
+ mean = mean_bytes(col)
188
+ bands = [b for b in by_age.get("bands") or [] if float(b.get("mean_bytes") or 0) > 0]
189
+ if not mean or len(bands) < 2 or by_age.get("unit") not in AGE_UNITS or not by_age.get("column"):
190
+ return []
191
+ return [(b.get("up_to"), round(float(b["mean_bytes"]) / mean, 4)) for b in bands]
192
+
193
+
194
+ def scaled(col: dict, factor: float) -> dict:
195
+ """The column with every stated size multiplied (rows that are heavier or lighter than the table's average)."""
196
+ out = dict(col)
197
+ for k in ("typical_bytes", "large_bytes", "mean_bytes", "avg_len"):
198
+ if out.get(k):
199
+ out[k] = max(int(round(float(out[k]) * factor)), 1)
200
+ return out