@capagents/forgeqe 2.10.5 → 3.0.1

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 (113) hide show
  1. package/HOW_TO_USE.md +104 -19
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/dist/docs-site/docs/index.html +97 -16
  4. package/dist/docs-site/docs/mobile/index.html +8 -0
  5. package/dist/docs-site/docs/search.js +1 -1
  6. package/dist/forgeqe.js +1950 -1932
  7. package/dist/web/assets/Agent-BqVEwTVC.js +8 -0
  8. package/dist/web/assets/ApiTests-DCatslaV.js +10 -0
  9. package/dist/web/assets/Browse-Bl8Qmv19.js +2 -0
  10. package/dist/web/assets/Chat-CclDgwrO.js +5 -0
  11. package/dist/web/assets/{CommandPalette-D7ufvlUN.js → CommandPalette-yhEQVq1q.js} +1 -1
  12. package/dist/web/assets/Compare-y9bBCySM.js +1 -0
  13. package/dist/web/assets/{Cost-DGZ5t-Q_.js → Cost-DJ3HO9gf.js} +1 -1
  14. package/dist/web/assets/{Data-DqGA1ZtQ.js → Data-HZP8SHLn.js} +4 -4
  15. package/dist/web/assets/Desktop-CI6C43R3.js +1 -0
  16. package/dist/web/assets/DesktopReview-CGDj4Ujf.js +1 -0
  17. package/dist/web/assets/Evidence-C1Vyg39z.js +1 -0
  18. package/dist/web/assets/{Explore-TtfTWmGW.js → Explore-BPWjMsOz.js} +2 -2
  19. package/dist/web/assets/{Features-DazoSiEi.js → Features-BXBE6r6G.js} +1 -1
  20. package/dist/web/assets/{Flags-Brja-ZXF.js → Flags-gDtVVBId.js} +2 -2
  21. package/dist/web/assets/Flaky-h8C09CFf.js +1 -0
  22. package/dist/web/assets/Impact-BT55F8b-.js +3 -0
  23. package/dist/web/assets/Jobs-BZJxI0NN.js +5 -0
  24. package/dist/web/assets/KindPage-DtUCsf9W.js +6 -0
  25. package/dist/web/assets/Migration-DTauoKTG.js +2 -0
  26. package/dist/web/assets/Product-CvKbCdHY.js +7 -0
  27. package/dist/web/assets/Production-CJQsBg05.js +1 -0
  28. package/dist/web/assets/{Quality-C4Aak_hw.js → Quality-CjipajoK.js} +1 -1
  29. package/dist/web/assets/Readiness-LaLczR5L.js +1 -0
  30. package/dist/web/assets/Record-TQ_WSnsE.js +2 -0
  31. package/dist/web/assets/Regression-CrjROhTU.js +5 -0
  32. package/dist/web/assets/{RelationGraph-DLeEarQd.js → RelationGraph-eoGXXz5t.js} +1 -1
  33. package/dist/web/assets/{Reports-ClSAzQOh.js → Reports-BTF2tHQN.js} +2 -2
  34. package/dist/web/assets/{Response-De60pk_7.js → Response-Dm1See-Y.js} +3 -9
  35. package/dist/web/assets/{RunDiff-0ibEcmI5.js → RunDiff-B6t56dwu.js} +1 -1
  36. package/dist/web/assets/{Runs-T8yF8Hi0.js → Runs-Oj-NO8Vl.js} +2 -2
  37. package/dist/web/assets/{Steps-CB30w6BA.js → Steps-Cm-atRtk.js} +2 -2
  38. package/dist/web/assets/TestCases-SL9YqWlm.js +1 -0
  39. package/dist/web/assets/TestData-C6j4ZbaF.js +2 -0
  40. package/dist/web/assets/TestDebt-CISwXKl-.js +1 -0
  41. package/dist/web/assets/Tosca-DTVz50ex.js +3 -0
  42. package/dist/web/assets/{WhatsNew-D7n48IsG.js → WhatsNew-2AgkrdMk.js} +1 -1
  43. package/dist/web/assets/agentLink-DfJdkmLQ.js +1 -0
  44. package/dist/web/assets/{dataParts-CZAcb4L_.js → dataParts-BwxK_p1D.js} +3 -3
  45. package/dist/web/assets/{families-D2ygriY6.js → families-DPlFfKf2.js} +1 -1
  46. package/dist/web/assets/filters-Bj5K1WaL.js +1 -0
  47. package/dist/web/assets/{fold-BhYvId2X.js → fold-BD-sox6G.js} +1 -1
  48. package/dist/web/assets/frame-B428t9gN.js +18 -0
  49. package/dist/web/assets/index-BtYlZE0c.js +67 -0
  50. package/dist/web/assets/index-DUWIa2Tp.css +2 -0
  51. package/dist/web/assets/{logos-DmK40tlV.js → logos-DCsyIKX5.js} +1 -1
  52. package/dist/web/assets/{markdown-Bej6qyls.js → markdown-6z0km3hN.js} +3 -3
  53. package/dist/web/assets/paletteCommands-3NG1WPGZ.js +1 -0
  54. package/dist/web/assets/{parts-BOpbd90H.js → parts-VPcxh6Jc.js} +1 -1
  55. package/dist/web/assets/{productParts-B3_FGd-T.js → productParts-BjfWgMtq.js} +1 -1
  56. package/dist/web/assets/{qualityParts-B8yJRVpP.js → qualityParts-BA-1cidT.js} +1 -1
  57. package/dist/web/assets/{recordTest-CZUrGm8I.js → recordTest-EkxSMWbe.js} +1 -1
  58. package/dist/web/assets/{rows-BcG6gFCy.js → rows-BOGSBviK.js} +1 -1
  59. package/dist/web/assets/{segmented-ffWUfF8N.js → segmented-DphDskQz.js} +1 -1
  60. package/dist/web/assets/{usePageChat-T6vQY_1C.js → usePageChat-Zg7SGziM.js} +1 -1
  61. package/dist/web/index.html +5 -5
  62. package/docs/MOBILE.md +9 -0
  63. package/docs/user-guide.html +97 -16
  64. package/forgeqe.example.yaml +2 -0
  65. package/package.json +3 -1
  66. package/prompts/brain.md +3 -2
  67. package/prompts/requests-rule.md +1 -1
  68. package/prompts/talk-summary.md +43 -0
  69. package/prompts/talk.md +63 -0
  70. package/prompts/test-agent.md +2 -1
  71. package/py/forgeqe_data/__init__.py +1 -0
  72. package/py/forgeqe_data/__main__.py +12 -0
  73. package/py/forgeqe_data/connect.py +290 -0
  74. package/py/forgeqe_data/connstr.py +169 -0
  75. package/py/forgeqe_data/flows.py +603 -0
  76. package/py/forgeqe_data/guard.py +214 -0
  77. package/py/forgeqe_data/mongo.py +219 -0
  78. package/py/forgeqe_data/schema.py +431 -0
  79. package/py/forgeqe_data/service.py +651 -0
  80. package/py/forgeqe_data/streams.py +400 -0
  81. package/py/forgeqe_data/subset.py +299 -0
  82. package/py/forgeqe_data/testdata.py +861 -0
  83. package/py/forgeqe_data/vector.py +113 -0
  84. package/py/forgeqe_talk/__init__.py +1 -0
  85. package/py/forgeqe_talk/__main__.py +65 -0
  86. package/py/forgeqe_voice/worker.py +24 -4
  87. package/dist/web/assets/Agent-bSVNDlcU.js +0 -8
  88. package/dist/web/assets/ApiTests-DOxGgoZC.js +0 -10
  89. package/dist/web/assets/Browse-CG8jzqR1.js +0 -2
  90. package/dist/web/assets/Chat-DzufzeGg.js +0 -5
  91. package/dist/web/assets/Compare-6vHuAaKv.js +0 -1
  92. package/dist/web/assets/Desktop-CSOFE8cN.js +0 -1
  93. package/dist/web/assets/DesktopReview-BWtionFH.js +0 -1
  94. package/dist/web/assets/Evidence-D8pLFcbr.js +0 -1
  95. package/dist/web/assets/Flaky-jJlHFFCa.js +0 -1
  96. package/dist/web/assets/Impact-b60dmhJK.js +0 -3
  97. package/dist/web/assets/Jobs-Y9W9nBgx.js +0 -5
  98. package/dist/web/assets/KindPage-Y72w2UwG.js +0 -6
  99. package/dist/web/assets/Migration-CvIeTB9p.js +0 -2
  100. package/dist/web/assets/Product-BEe2GyO6.js +0 -7
  101. package/dist/web/assets/Production-D2qmPFYy.js +0 -1
  102. package/dist/web/assets/Readiness-ClXnnmLo.js +0 -1
  103. package/dist/web/assets/Record-LaLYhQgk.js +0 -2
  104. package/dist/web/assets/Regression-DKz05MC_.js +0 -5
  105. package/dist/web/assets/TestCases-Ba6bUE4i.js +0 -1
  106. package/dist/web/assets/TestData-DefDzeMW.js +0 -2
  107. package/dist/web/assets/TestDebt-zohltDHp.js +0 -1
  108. package/dist/web/assets/Tosca-jAtdiG28.js +0 -3
  109. package/dist/web/assets/filters-CYaF2RvC.js +0 -1
  110. package/dist/web/assets/frame-DeJBYtBX.js +0 -11
  111. package/dist/web/assets/index-CYlacOTX.css +0 -2
  112. package/dist/web/assets/index-DXpBYobT.js +0 -67
  113. package/dist/web/assets/paletteCommands-CKBMmhb4.js +0 -1
@@ -0,0 +1,603 @@
1
+ """
2
+ Data flows between databases: a system that writes a record (the digital channel's database) and the systems it
3
+ reaches (CRM, billing, a warehouse), by batch ETL or in real time. A flow is one hop, source table to target table:
4
+
5
+ signup_to_crm:
6
+ from: {db: digital, table: customers, key: id, changed: updated_at}
7
+ to: {db: crm, table: contacts, key: source_customer_id}
8
+ mode: realtime # or batch
9
+ sla: 15m # realtime: a source row older than this must have arrived
10
+ ready: {sql: "SELECT MAX(finished_at) FROM etl_runs WHERE job = 'signup'"} # batch: a run after the check began
11
+ since: 7d # only source rows changed in the last 7 days (needs changed:)
12
+ columns:
13
+ email: {to: email_address, rule: lower}
14
+ name: {to: full_name, rule: trim}
15
+ country: {to: country_code, map: {India: IN, United Kingdom: GB}}
16
+ total: {to: amount, rule: "round(2)"}
17
+ full_name: {to: display, template: "{first_name} {last_name}"}
18
+
19
+ Checks, all reads in read-only sessions:
20
+ - completeness: every source key is in the target (missing), and with extra: true no target key lacks a source;
21
+ - correctness: each mapped column, after its rule, equals the target's value (mismatches with key and values);
22
+ - timeliness (realtime): a missing row is late once its change is older than the SLA, else still in flight;
23
+ - duplicates: a target key that appears more than once;
24
+ - readiness (batch): the ready query's value after the check began, waited for up to wait seconds.
25
+
26
+ Keys go to the databases as bound parameters, a thousand at a time; at most MAX_KEYS source rows are compared.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import datetime as dt
31
+ import decimal
32
+ import json
33
+ import re
34
+ import time
35
+ from dataclasses import dataclass, field
36
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Set, Tuple
37
+
38
+ from . import guard
39
+
40
+ MAX_KEYS = 200_000
41
+ CHUNK = 1000
42
+ SHOW = 25
43
+ _DURATION = re.compile(r"^(\d+)\s*([smhd])$")
44
+ RULES = ("same", "lower", "upper", "trim", "date", "number", "string")
45
+
46
+
47
+ class FlowError(ValueError):
48
+ pass
49
+
50
+
51
+ def seconds(text: Any, where: str) -> int:
52
+ m = _DURATION.match(str(text or "").strip().lower())
53
+ if not m:
54
+ raise FlowError(f"{where}: a duration such as 30s, 15m, 6h or 7d")
55
+ return int(m.group(1)) * {"s": 1, "m": 60, "h": 3600, "d": 86400}[m.group(2)]
56
+
57
+
58
+ @dataclass
59
+ class Side:
60
+ db: str
61
+ table: str
62
+ key: str
63
+ changed: str = ""
64
+ # A Kafka topic of a databases: entry with engine: kafka (table holds the topic's name too), or an API app's path.
65
+ topic: str = ""
66
+ api: str = ""
67
+ path: str = ""
68
+ # An API's call: GET or POST, a body with {key} in it, where the records are in a response, its next page link.
69
+ method: str = "GET"
70
+ body: Any = None
71
+ items: str = ""
72
+ next: str = ""
73
+
74
+ @property
75
+ def label(self) -> str:
76
+ return f"api:{self.api}{self.path}" if self.api else f"{self.db}.{self.table}"
77
+
78
+
79
+ @dataclass
80
+ class ColumnMap:
81
+ source: str
82
+ target: str
83
+ rule: str = "same"
84
+ places: Optional[int] = None
85
+ mapping: Optional[Dict[str, Any]] = None
86
+ template: str = ""
87
+ default: Any = None
88
+
89
+
90
+ @dataclass
91
+ class Flow:
92
+ name: str
93
+ src: Side
94
+ dst: Side
95
+ mode: str = "batch"
96
+ sla: Optional[int] = None
97
+ since: Optional[int] = None
98
+ ready: Optional[str] = None
99
+ wait: int = 0
100
+ extra: bool = False
101
+ columns: List[ColumnMap] = field(default_factory=list)
102
+
103
+
104
+ def _side(raw: Any, where: str) -> Side:
105
+ """A table {db, table, key}, a Kafka topic {db, topic, key}, or an API {api, path, key, method, body, items, next}."""
106
+ if not isinstance(raw, dict):
107
+ raise FlowError(f"{where}: {{db, table, key}}, {{db, topic, key}} or {{api, path, key}}")
108
+ name = re.compile(r"[\w$#.-]+")
109
+ field = re.compile(r"\$?[\w#-]+(\.[\w$#-]+)*")
110
+ key = raw.get("key")
111
+ if not isinstance(key, str) or not field.fullmatch(key):
112
+ raise FlowError(f"{where}.key: a column, or a field of the message or response (customer.id, $key)")
113
+ changed = str(raw.get("changed") or "")
114
+ if changed and not field.fullmatch(changed):
115
+ raise FlowError(f"{where}.changed: a column or field")
116
+ if raw.get("api"):
117
+ api, path = str(raw["api"]), str(raw.get("path") or "")
118
+ if not name.fullmatch(api) or not path.startswith("/") or "://" in path or ".." in path:
119
+ raise FlowError(f"{where}: an API side is {{api: an API app of the environment, path: /contacts/{{key}} (a target) or /contacts (a source), key: the response's field}}")
120
+ method = str(raw.get("method") or "GET").upper()
121
+ if method not in ("GET", "POST"):
122
+ raise FlowError(f"{where}.method: GET or POST (a lookup or a search); a check never changes data, so {method} is refused")
123
+ body = raw.get("body")
124
+ if body is not None and (method != "POST" or not isinstance(body, (dict, list, str))):
125
+ raise FlowError(f"{where}.body: the JSON a POST sends, with {{key}} where the key goes")
126
+ items, nxt = str(raw.get("items") or ""), str(raw.get("next") or "")
127
+ for k, v in (("items", items), ("next", nxt)):
128
+ if v and not field.fullmatch(v):
129
+ raise FlowError(f"{where}.{k}: a dotted field of the response (data.items)")
130
+ return Side("", "", key, changed, api=api, path=path, method=method, body=body, items=items, next=nxt)
131
+ db = raw.get("db")
132
+ table = raw.get("topic") or raw.get("table")
133
+ for k, v in (("db", db), ("table or topic", table)):
134
+ if not isinstance(v, str) or not name.fullmatch(v):
135
+ raise FlowError(f"{where}.{k} is required: a name")
136
+ return Side(str(db), str(table), key, changed, topic=str(raw.get("topic") or ""))
137
+
138
+
139
+ def parse(name: str, raw: Mapping[str, Any]) -> Flow:
140
+ where = f"flows.{name}"
141
+ if not re.fullmatch(r"[A-Za-z0-9][\w.-]{0,63}", name):
142
+ raise FlowError(f"{where}: flow names are letters, digits and _ . -")
143
+ if not isinstance(raw, dict):
144
+ raise FlowError(f"{where} is a mapping with from, to and columns")
145
+ f = Flow(name, _side(raw.get("from"), f"{where}.from"), _side(raw.get("to"), f"{where}.to"))
146
+ for side, label in ((f.src, "from"), (f.dst, "to")):
147
+ by_key = side.api and ("{key}" in side.path or "{key}" in json.dumps(side.body, default=str))
148
+ if side.api and label == "from" and by_key:
149
+ raise FlowError(f"{where}.from: an API source is a list endpoint (path: /contacts, no {{key}}); one that answers for a key can be a target")
150
+ if side.api and label == "to" and not by_key:
151
+ raise FlowError(f"{where}.to: an API target answers for one key: put {{key}} in its path (/contacts/{{key}}) or its body")
152
+ if side.api and label == "to" and side.next:
153
+ raise FlowError(f"{where}.to.next: only a source's list has pages")
154
+ if f.src.topic and not f.src.changed:
155
+ f.src.changed = "$timestamp"
156
+ f.mode = str(raw.get("mode") or "batch")
157
+ if f.mode not in ("batch", "realtime"):
158
+ raise FlowError(f"{where}.mode is batch or realtime")
159
+ if raw.get("sla") is not None:
160
+ f.sla = seconds(raw["sla"], f"{where}.sla")
161
+ if raw.get("since") is not None:
162
+ f.since = seconds(raw["since"], f"{where}.since")
163
+ if not f.src.changed:
164
+ raise FlowError(f"{where}.since needs from.changed: the source column that says when a row changed")
165
+ if f.mode == "realtime" and f.sla and not f.src.changed:
166
+ raise FlowError(f"{where}.sla needs from.changed: the source column that says when a row changed")
167
+ ready = raw.get("ready")
168
+ if ready is not None and (f.dst.api or f.dst.topic):
169
+ raise FlowError(f"{where}.ready is a query on the target database; an API or a topic has none")
170
+ if raw.get("extra") is True and f.dst.api:
171
+ raise FlowError(f"{where}.extra: an API cannot list its records, only answer for each key")
172
+ if ready is not None:
173
+ if not isinstance(ready, dict) or not isinstance(ready.get("sql"), str):
174
+ raise FlowError(f"{where}.ready is {{sql: a query whose one value is when the last run finished}}")
175
+ f.ready = ready["sql"]
176
+ f.wait = seconds(ready.get("wait", "0s"), f"{where}.ready.wait") if ready.get("wait") else 0
177
+ f.extra = raw.get("extra") is True
178
+ cols = raw.get("columns") or {}
179
+ if not isinstance(cols, dict):
180
+ raise FlowError(f"{where}.columns maps source columns to {{to, rule}}")
181
+ for src, spec in cols.items():
182
+ cw = f"{where}.columns.{src}"
183
+ if isinstance(spec, str):
184
+ spec = {"to": spec}
185
+ if not isinstance(spec, dict) or not isinstance(spec.get("to"), str):
186
+ raise FlowError(f"{cw}: {{to: target column, rule: ...}}")
187
+ c = ColumnMap(str(src), spec["to"], default=spec.get("default"))
188
+ rule = str(spec.get("rule") or "same").strip().lower()
189
+ m = re.fullmatch(r"round\((\d)\)", rule)
190
+ if m:
191
+ c.rule, c.places = "round", int(m.group(1))
192
+ elif rule in RULES:
193
+ c.rule = rule
194
+ else:
195
+ raise FlowError(f"{cw}.rule is one of {', '.join(RULES)} or round(n); a lookup is map: {{source value: target value}} and a combination is template: \"{{first_name}} {{last_name}}\", each beside to:")
196
+ if spec.get("map") is not None:
197
+ if not isinstance(spec["map"], dict):
198
+ raise FlowError(f"{cw}.map maps source values to target values")
199
+ c.mapping = {str(k): v for k, v in spec["map"].items()}
200
+ if spec.get("template") is not None:
201
+ c.template = str(spec["template"])
202
+ guard_fields(c.template, cw)
203
+ f.columns.append(c)
204
+ return f
205
+
206
+
207
+ def guard_fields(template: str, where: str) -> List[str]:
208
+ import string
209
+
210
+ out = []
211
+ for _, name, spec, conv in string.Formatter().parse(template):
212
+ if name is None:
213
+ continue
214
+ if not re.fullmatch(r"[A-Za-z_][\w$#]*", name) or conv or (spec and "{" in spec):
215
+ raise FlowError(f"{where}.template: {{{name}}} is not allowed; name source columns, as {{first_name}}")
216
+ out.append(name)
217
+ return out
218
+
219
+
220
+ def check_names(f: Flow, src_cat: Mapping[str, Any], dst_cat: Mapping[str, Any]) -> List[str]:
221
+ """What in the flow names a table or column the databases do not have (topics and APIs are checked when read)."""
222
+ problems = []
223
+ for side, cat, label in ((f.src, src_cat, "from"), (f.dst, dst_cat, "to")):
224
+ if side.api or side.topic:
225
+ continue
226
+ t = (cat.get("tables") or {}).get(side.table)
227
+ if not t:
228
+ problems.append(f"{label}.table {side.table} is not in {side.db}")
229
+ continue
230
+ cols = {c["name"] for c in t["columns"]}
231
+ for col in [side.key, side.changed] if side.changed else [side.key]:
232
+ if col not in cols:
233
+ problems.append(f"{label}: {side.table} has no column {col}")
234
+ st = None if f.src.topic else (src_cat.get("tables") or {}).get(f.src.table)
235
+ dt_ = None if (f.dst.api or f.dst.topic) else (dst_cat.get("tables") or {}).get(f.dst.table)
236
+ if st and dt_:
237
+ scols = {c["name"] for c in st["columns"]}
238
+ dcols = {c["name"] for c in dt_["columns"]}
239
+ for c in f.columns:
240
+ needed = guard_fields(c.template, c.source) if c.template else [c.source]
241
+ for n in needed:
242
+ if n not in scols:
243
+ problems.append(f"columns.{c.source}: {f.src.table} has no column {n}")
244
+ if c.target not in dcols:
245
+ problems.append(f"columns.{c.source}: {f.dst.table} has no column {c.target}")
246
+ return problems
247
+
248
+
249
+ # ------------------------------------------------------------------------------------------------ values
250
+
251
+
252
+ def _norm(v: Any) -> Any:
253
+ """
254
+ Values from different databases made comparable: numbers as decimals, date-times to the second as ISO text, and
255
+ text without trailing spaces (CHAR columns pad them, and databases pad differently).
256
+ """
257
+ if v is None:
258
+ return None
259
+ if isinstance(v, bool):
260
+ return v
261
+ if isinstance(v, (int, float, decimal.Decimal)):
262
+ return decimal.Decimal(str(v))
263
+ if isinstance(v, dt.datetime):
264
+ return v.replace(tzinfo=None, microsecond=0).isoformat()
265
+ if isinstance(v, dt.date):
266
+ return v.isoformat()
267
+ if isinstance(v, (bytes, bytearray, memoryview)):
268
+ return bytes(v).hex()
269
+ return str(v).rstrip(" ")
270
+
271
+
272
+ _ISO_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}:\d{2})?")
273
+
274
+
275
+ def expected(c: ColumnMap, row: Mapping[str, Any]) -> Any:
276
+ """The value the target should hold for this source row."""
277
+ if c.template:
278
+ value: Any = c.template.format(**{k: "" if v is None else v for k, v in row.items()})
279
+ else:
280
+ value = row.get(c.source)
281
+ if value is None:
282
+ return c.default
283
+ if c.mapping is not None:
284
+ key = str(value)
285
+ if key in c.mapping:
286
+ value = c.mapping[key]
287
+ if c.rule == "lower":
288
+ value = str(value).lower()
289
+ elif c.rule == "upper":
290
+ value = str(value).upper()
291
+ elif c.rule == "trim":
292
+ value = str(value).strip()
293
+ elif c.rule == "round":
294
+ # Half up, as databases and ETL tools round (Python's round() goes half to even: 54.005 would be 54.00).
295
+ value = decimal.Decimal(str(value)).quantize(decimal.Decimal(1).scaleb(-(c.places or 0)), rounding=decimal.ROUND_HALF_UP)
296
+ elif c.rule == "date":
297
+ value = value.date() if isinstance(value, dt.datetime) else value
298
+ elif c.rule == "number":
299
+ value = decimal.Decimal(str(value))
300
+ elif c.rule == "string":
301
+ value = str(value)
302
+ return value
303
+
304
+
305
+ def same(a: Any, b: Any) -> bool:
306
+ na, nb = _norm(a), _norm(b)
307
+ if isinstance(na, decimal.Decimal) and isinstance(nb, decimal.Decimal):
308
+ return na == nb
309
+ if isinstance(na, decimal.Decimal) or isinstance(nb, decimal.Decimal):
310
+ try:
311
+ return decimal.Decimal(str(na)) == decimal.Decimal(str(nb))
312
+ except (decimal.InvalidOperation, ValueError):
313
+ return False
314
+ if isinstance(na, str) and isinstance(nb, str) and _ISO_DATE.match(na) and _ISO_DATE.match(nb):
315
+ # The same moment written with a T or a space; a date and that date at midnight.
316
+ a, b = na.replace(" ", "T")[:19], nb.replace(" ", "T")[:19]
317
+ return a == b or (len(a) == 10 and b == f"{a}T00:00:00") or (len(b) == 10 and a == f"{b}T00:00:00")
318
+ return na == nb
319
+
320
+
321
+ def _plain(v: Any) -> Any:
322
+ n = _norm(v)
323
+ return str(n) if isinstance(n, decimal.Decimal) else n
324
+
325
+
326
+ # ------------------------------------------------------------------------------------------------ reading
327
+
328
+
329
+ class Reader:
330
+ """Rows of one table of one database, read-only, by key or by a window of change."""
331
+
332
+ def __init__(self, engine: Any, engine_name: str, schema: Optional[str], table: str) -> None:
333
+ from sqlalchemy import MetaData, Table
334
+
335
+ self.engine = engine
336
+ self.engine_name = engine_name
337
+ self.conn = engine.connect()
338
+ self.table = Table(table, MetaData(schema=schema), autoload_with=self.conn)
339
+
340
+ def close(self) -> None:
341
+ try:
342
+ self.conn.rollback()
343
+ finally:
344
+ self.conn.close()
345
+
346
+ def keys(self, key: str, changed: str = "", since: Optional[dt.datetime] = None, limit: int = MAX_KEYS) -> List[Tuple[Any, Any]]:
347
+ """(key, changed) of every row, or of those changed since; at most limit, by key."""
348
+ from sqlalchemy import select
349
+
350
+ t = self.table
351
+ cols = [t.c[key]] + ([t.c[changed]] if changed else [])
352
+ q = select(*cols)
353
+ if since is not None and changed:
354
+ q = q.where(t.c[changed] >= since)
355
+ rows = self.conn.execute(q.order_by(t.c[key]).limit(limit + 1)).fetchall()
356
+ return [(r[0], r[1] if changed else None) for r in rows]
357
+
358
+ def rows(self, key: str, values: Sequence[Any]) -> Dict[Any, List[Dict[str, Any]]]:
359
+ """Rows by key value; a key that appears twice keeps both."""
360
+ from sqlalchemy import select
361
+
362
+ t = self.table
363
+ out: Dict[Any, List[Dict[str, Any]]] = {}
364
+ vals = list(values)
365
+ for i in range(0, len(vals), CHUNK):
366
+ for r in self.conn.execute(select(t).where(t.c[key].in_(vals[i : i + CHUNK]))).fetchall():
367
+ m = dict(r._mapping)
368
+ out.setdefault(_key(m[key]), []).append(m)
369
+ return out
370
+
371
+ def find(self, key: str, where: Mapping[str, Any]) -> Any:
372
+ """The key of the newest row whose columns hold these values (the record a test just made), or None."""
373
+ from sqlalchemy import and_, select
374
+
375
+ t = self.table
376
+ unknown = [c for c in where if c not in t.c]
377
+ if unknown:
378
+ raise FlowError(f"where: {t.name} has no column {', '.join(unknown)}")
379
+ row = self.conn.execute(select(t.c[key]).where(and_(*[t.c[c] == v for c, v in where.items()])).order_by(t.c[key].desc()).limit(1)).first()
380
+ return _key(row[0]) if row else None
381
+
382
+ def duplicates(self, key: str, limit: int = SHOW) -> List[Tuple[Any, int]]:
383
+ from sqlalchemy import func, select
384
+
385
+ t = self.table
386
+ q = select(t.c[key], func.count()).group_by(t.c[key]).having(func.count() > 1).limit(limit)
387
+ return [(r[0], int(r[1])) for r in self.conn.execute(q).fetchall()]
388
+
389
+ def scalar(self, sql: str) -> Any:
390
+ from sqlalchemy import text
391
+
392
+ verdict = guard.check(sql, self.engine_name)
393
+ if not verdict.ok:
394
+ raise FlowError(f"ready.sql: {verdict.reason}")
395
+ return self.conn.execute(text(verdict.sql)).scalar()
396
+
397
+
398
+ def _key(v: Any) -> Any:
399
+ """Keys compared across databases: 42, 42.0 and '42' are the same key."""
400
+ if isinstance(v, (int, decimal.Decimal, float)) and not isinstance(v, bool):
401
+ d = decimal.Decimal(str(v))
402
+ return int(d) if d == d.to_integral_value() else str(d)
403
+ if isinstance(v, str) and re.fullmatch(r"-?\d+", v.strip()):
404
+ return int(v.strip())
405
+ return v if not isinstance(v, str) else v.strip()
406
+
407
+
408
+ def _naive(v: Any) -> Optional[dt.datetime]:
409
+ if isinstance(v, dt.datetime):
410
+ return v.replace(tzinfo=None) if v.tzinfo is None else v.astimezone(dt.timezone.utc).replace(tzinfo=None)
411
+ if isinstance(v, dt.date):
412
+ return dt.datetime.combine(v, dt.time())
413
+ return None
414
+
415
+
416
+ # ------------------------------------------------------------------------------------------------ checks
417
+
418
+
419
+ def check(f: Flow, src: Reader, dst: Reader, *, now: Optional[dt.datetime] = None, began: Optional[dt.datetime] = None,
420
+ mask: Callable[[str], bool] = lambda _: False, log: Callable[[str], None] = lambda _: None) -> Dict[str, Any]:
421
+ """One flow's checks; ok when nothing is missing, wrong, late or duplicated."""
422
+ now = now or dt.datetime.utcnow()
423
+ began = began or now
424
+ result: Dict[str, Any] = {"flow": f.name, "from": f.src.label, "to": f.dst.label, "mode": f.mode}
425
+
426
+ if f.ready:
427
+ waited = 0
428
+ while True:
429
+ value = dst.scalar(f.ready)
430
+ finished = _naive(value)
431
+ if finished is not None and finished >= began - dt.timedelta(seconds=1):
432
+ result["ready"] = {"finished": finished.isoformat(), "waited": waited}
433
+ break
434
+ if waited >= f.wait:
435
+ result["ready"] = {"finished": finished.isoformat() if finished else None, "waited": waited, "stale": True}
436
+ result["note"] = "No run of the job finished after the check began; the rows checked are from the last run."
437
+ break
438
+ log(f"{f.name}: waiting for the job to finish ({waited}s of {f.wait}s)")
439
+ time.sleep(5)
440
+ dst.conn.rollback()
441
+ waited += 5
442
+
443
+ window = now - dt.timedelta(seconds=f.since) if f.since else None
444
+ source = src.keys(f.src.key, f.src.changed, window)
445
+ truncated = len(source) > MAX_KEYS
446
+ source = source[:MAX_KEYS]
447
+ changed_at = {_key(k): _naive(c) for k, c in source}
448
+ keys = list(changed_at)
449
+ log(f"{f.name}: {len(keys)} source rows to compare")
450
+ src_rows = src.rows(f.src.key, [k for k, _ in source])
451
+ dst_rows = dst.rows(f.dst.key, keys)
452
+
453
+ missing = [k for k in keys if k not in dst_rows]
454
+ late: List[Any] = []
455
+ in_flight: List[Any] = []
456
+ if f.mode == "realtime" and f.sla and f.src.changed:
457
+ for k in missing:
458
+ at = changed_at.get(k)
459
+ (late if at is None or (now - at).total_seconds() > f.sla else in_flight).append(k)
460
+ dupes_here = [(k, len(v)) for k, v in dst_rows.items() if len(v) > 1]
461
+
462
+ mismatches: List[Dict[str, Any]] = []
463
+ wrong_rows: Set[Any] = set()
464
+ per_column: Dict[str, int] = {}
465
+ for k in keys:
466
+ if k not in dst_rows or k not in src_rows:
467
+ continue
468
+ s, d = src_rows[k][0], dst_rows[k][0]
469
+ for c in f.columns:
470
+ want, got = expected(c, s), d.get(c.target)
471
+ if not same(want, got):
472
+ wrong_rows.add(k)
473
+ per_column[c.source] = per_column.get(c.source, 0) + 1
474
+ if len(mismatches) < SHOW:
475
+ hide = mask(c.source) or mask(c.target)
476
+ mismatches.append({"key": k, "column": f"{c.source} -> {c.target}", "rule": c.rule if not c.mapping else "map", "source": "•••" if hide else _plain(s.get(c.source)), "expected": "•••" if hide else _plain(want), "target": "•••" if hide else _plain(got)})
477
+
478
+ extra: List[Any] = []
479
+ if f.extra:
480
+ target_keys = {_key(k) for k, _ in dst.keys(f.dst.key)}
481
+ all_source = {_key(k) for k, _ in src.keys(f.src.key)} if window else set(keys)
482
+ extra = sorted((target_keys - all_source), key=str)
483
+
484
+ failures = (len(late) if f.mode == "realtime" and f.sla else len(missing)) + len(wrong_rows) + len(dupes_here) + len(extra)
485
+ result.update({
486
+ "ok": failures == 0,
487
+ "source_rows": len(keys),
488
+ "matched": len(keys) - len(missing),
489
+ "missing": {"count": len(missing), "keys": missing[:SHOW]},
490
+ **({"late": {"count": len(late), "keys": late[:SHOW], "sla_seconds": f.sla}, "in_flight": {"count": len(in_flight), "keys": in_flight[:SHOW]}} if f.mode == "realtime" and f.sla else {}),
491
+ "wrong": {"rows": len(wrong_rows), "by_column": per_column, "examples": mismatches},
492
+ "duplicates": {"count": len(dupes_here), "keys": [{"key": k, "times": n} for k, n in dupes_here[:SHOW]]},
493
+ **({"extra": {"count": len(extra), "keys": extra[:SHOW]}} if f.extra else {}),
494
+ **({"truncated": f"only the first {MAX_KEYS} source rows by key were compared"} if truncated else {}),
495
+ **({"window": f"rows changed since {window.isoformat(timespec='seconds')}"} if window else {}),
496
+ })
497
+ return result
498
+
499
+
500
+ def trace(chain: List[Tuple[Flow, Reader, Reader]], key: Any, *, wait: int = 0, mask: Callable[[str], bool] = lambda _: False,
501
+ log: Callable[[str], None] = lambda _: None) -> List[Dict[str, Any]]:
502
+ """
503
+ One record along a chain of flows: at each hop, whether it arrived, how its mapped columns compare, and its key on
504
+ the next hop (the target's key of that hop's source table). Waits up to `wait` seconds for each hop to arrive.
505
+ """
506
+ hops: List[Dict[str, Any]] = []
507
+ current = _key(key)
508
+ for f, src, dst in chain:
509
+ s = src.rows(f.src.key, [current]).get(current)
510
+ hop: Dict[str, Any] = {"flow": f.name, "from": f.src.label, "to": f.dst.label, "key": current}
511
+ if not s:
512
+ hop.update({"ok": False, "found_in_source": False})
513
+ hops.append(hop)
514
+ break
515
+ waited = 0
516
+ d = dst.rows(f.dst.key, [current]).get(current)
517
+ while not d and waited < wait:
518
+ log(f"{f.name}: {current} has not arrived in {f.dst.label} yet ({waited}s)")
519
+ time.sleep(3)
520
+ waited += 3
521
+ dst.conn.rollback()
522
+ d = dst.rows(f.dst.key, [current]).get(current)
523
+ if not d:
524
+ hop.update({"ok": False, "arrived": False, "waited": waited})
525
+ hops.append(hop)
526
+ break
527
+ diffs = []
528
+ for c in f.columns:
529
+ want, got = expected(c, s[0]), d[0].get(c.target)
530
+ if not same(want, got):
531
+ hide = mask(c.source) or mask(c.target)
532
+ diffs.append({"column": f"{c.source} -> {c.target}", "expected": "•••" if hide else _plain(want), "target": "•••" if hide else _plain(got)})
533
+ hop.update({"ok": not diffs and len(d) == 1, "arrived": True, "waited": waited, "copies": len(d), "differences": diffs})
534
+ hops.append(hop)
535
+ # The next hop starts from the row that arrived: its own key in its table.
536
+ nxt = chain[len(hops)] if len(hops) < len(chain) else None
537
+ if nxt is None:
538
+ break
539
+ current = _key(d[0].get(nxt[0].src.key))
540
+ return hops
541
+
542
+
543
+ # ------------------------------------------------------------------------------------------------ suggest
544
+
545
+ _TOKEN = re.compile(r"[a-z0-9]+")
546
+
547
+
548
+ def _tokens(name: str) -> Set[str]:
549
+ toks = set(_TOKEN.findall(re.sub(r"([a-z])([A-Z])", r"\1_\2", name).lower()))
550
+ return {t[:-1] if len(t) > 3 and t.endswith("s") else t for t in toks} - {"id", "tbl", "t"}
551
+
552
+
553
+ def suggest(src_cat: Mapping[str, Any], src_table: str, dst_cat: Mapping[str, Any], dst_table: str) -> Dict[str, Any]:
554
+ """A first draft of a flow between two tables: their key link and column pairs, by name and type; to be checked."""
555
+ s = src_cat["tables"][src_table]
556
+ d = dst_cat["tables"][dst_table]
557
+ spk = (s.get("pk") or ["id"])[0]
558
+ base = _tokens(src_table)
559
+ key_candidates = []
560
+ for c in d["columns"]:
561
+ toks = _tokens(c["name"])
562
+ name = c["name"].lower()
563
+ score = 0
564
+ if re.search(r"(source|src|origin|external|ext|legacy|upstream)", name):
565
+ score += 2
566
+ if toks & base:
567
+ score += 2
568
+ if name.endswith("_id") or name.endswith("id"):
569
+ score += 1
570
+ if c["name"] in (d.get("pk") or []):
571
+ score -= 2
572
+ if score >= 3:
573
+ key_candidates.append((score, c["name"]))
574
+ key_candidates.sort(reverse=True)
575
+ pairs = []
576
+ used: Set[str] = set()
577
+ for c in s["columns"]:
578
+ if c["name"] == spk:
579
+ continue
580
+ ct = _tokens(c["name"])
581
+ best, best_score = None, 0.0
582
+ for t in d["columns"]:
583
+ if t["name"] in used:
584
+ continue
585
+ tt = _tokens(t["name"])
586
+ overlap = len(ct & tt) / max(1, len(ct | tt))
587
+ if c["name"].lower() == t["name"].lower():
588
+ overlap = 1.0
589
+ if overlap > best_score:
590
+ best, best_score = t["name"], overlap
591
+ if best and best_score >= 0.5:
592
+ used.add(best)
593
+ pairs.append({"from": c["name"], "to": best, "confidence": round(best_score, 2)})
594
+ return {"from": {"table": src_table, "key": spk}, "to": {"table": dst_table, "key_candidates": [n for _, n in key_candidates[:3]]}, "columns": pairs}
595
+
596
+
597
+ def key_overlap(src: Reader, src_key: str, dst: Reader, dst_key: str, sample: int = 200) -> float:
598
+ """How many of a sample of source keys the target column holds: evidence that the two are the same key."""
599
+ keys = [k for k, _ in src.keys(src_key, limit=sample)][:sample]
600
+ if not keys:
601
+ return 0.0
602
+ found = dst.rows(dst_key, keys)
603
+ return round(len(found) / len(keys), 2)