@capagents/forgeqe 2.10.4 → 3.0.0
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.
- package/HOW_TO_USE.md +119 -16
- package/README.md +1 -1
- package/THIRD_PARTY_NOTICES.md +1 -0
- package/dist/docs-site/docs/architecture/index.html +1 -0
- package/dist/docs-site/docs/cost-architecture/index.html +1 -1
- package/dist/docs-site/docs/index.html +158 -19
- package/dist/docs-site/docs/mobile/index.html +38 -2
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/forgeqe.js +2121 -1947
- package/dist/web/assets/Agent-DISh0THc.js +8 -0
- package/dist/web/assets/ApiTests-CK0HqEH4.js +10 -0
- package/dist/web/assets/Browse-WylAQZvD.js +2 -0
- package/dist/web/assets/Chat-B7IOg3I3.js +5 -0
- package/dist/web/assets/CommandPalette-CkreEJ8R.js +1 -0
- package/dist/web/assets/Compare-CgOfZofk.js +1 -0
- package/dist/web/assets/Cost-Dl5-viu4.js +1 -0
- package/dist/web/assets/Data-Bv2S5wkW.js +6 -0
- package/dist/web/assets/Desktop-CifPwy5u.js +1 -0
- package/dist/web/assets/DesktopReview-fpGdtU4r.js +1 -0
- package/dist/web/assets/Evidence-hOZDzfKt.js +1 -0
- package/dist/web/assets/Explore-c85VGE9Q.js +2 -0
- package/dist/web/assets/Features-DXL_vSjn.js +1 -0
- package/dist/web/assets/Flags-B7x2pDud.js +2 -0
- package/dist/web/assets/Flaky-BM3syqCt.js +1 -0
- package/dist/web/assets/Impact-BUCh8OAI.js +3 -0
- package/dist/web/assets/Jobs-B8sBDYRI.js +5 -0
- package/dist/web/assets/KindPage-yVmpQm7L.js +6 -0
- package/dist/web/assets/Migration-BOLN1duU.js +2 -0
- package/dist/web/assets/Product-C0FeEaJg.js +7 -0
- package/dist/web/assets/Production-BSMQyWKd.js +1 -0
- package/dist/web/assets/Quality-DsM9gWZb.js +1 -0
- package/dist/web/assets/Readiness-BhqkAJYN.js +1 -0
- package/dist/web/assets/Record-CPx-lK53.js +2 -0
- package/dist/web/assets/Regression-BXbX46nO.js +5 -0
- package/dist/web/assets/{RelationGraph-D_ZVeOBh.js → RelationGraph-eoGXXz5t.js} +1 -1
- package/dist/web/assets/Reports-36YQzVhA.js +2 -0
- package/dist/web/assets/Response-DplUOsue.js +4 -0
- package/dist/web/assets/RunDiff-D0fDhRmK.js +1 -0
- package/dist/web/assets/Runs-Bv1Ef8zq.js +2 -0
- package/dist/web/assets/Steps-Cm-atRtk.js +2 -0
- package/dist/web/assets/TestCases-B9x9W3zJ.js +1 -0
- package/dist/web/assets/TestData-DsJ6Z2YI.js +2 -0
- package/dist/web/assets/TestDebt-B_FUbMOb.js +1 -0
- package/dist/web/assets/Tosca-nxVCubA5.js +3 -0
- package/dist/web/assets/WhatsNew-CdnbMvrr.js +1 -0
- package/dist/web/assets/agentLink-BGKAF6xd.js +1 -0
- package/dist/web/assets/capture.worklet-C2TjBQ56.js +11 -0
- package/dist/web/assets/capture.worklet-UcNywATd.js +1 -0
- package/dist/web/assets/dataParts-Bn-tzbKg.js +3 -0
- package/dist/web/assets/{families-zlLgApNV.js → families-DPlFfKf2.js} +1 -1
- package/dist/web/assets/filters-Bj5K1WaL.js +1 -0
- package/dist/web/assets/fold-BhRpA0sy.js +1 -0
- package/dist/web/assets/frame-D_TPoUTD.js +16 -0
- package/dist/web/assets/index-BRB-oAMd.js +67 -0
- package/dist/web/assets/index-CIw5WfL8.css +2 -0
- package/dist/web/assets/{line-icons-CQ-3V8ax.js → line-icons-DBwNPSmu.js} +1 -1
- package/dist/web/assets/{logos-DfCytw3-.js → logos-839CfoKx.js} +1 -1
- package/dist/web/assets/{markdown-nTIj9lyp.js → markdown-6z0km3hN.js} +7 -7
- package/dist/web/assets/paletteCommands-CZFdKGhh.js +1 -0
- package/dist/web/assets/parts-VPcxh6Jc.js +1 -0
- package/dist/web/assets/{productParts-DK3ULNpv.js → productParts-BjfWgMtq.js} +1 -1
- package/dist/web/assets/qualityParts-PGN65yfI.js +1 -0
- package/dist/web/assets/{recordTest-CqxnF953.js → recordTest-EkxSMWbe.js} +1 -1
- package/dist/web/assets/rows-uLoguIo5.js +1 -0
- package/dist/web/assets/segmented-DphDskQz.js +1 -0
- package/dist/web/assets/{usePageChat-Dl2aUtHP.js → usePageChat-DqEwGcyO.js} +1 -1
- package/dist/web/index.html +6 -6
- package/docs/ARCHITECTURE.md +1 -0
- package/docs/COST_ARCHITECTURE.md +1 -1
- package/docs/MOBILE.md +40 -0
- package/docs/user-guide.html +158 -19
- package/evals/prompts/brain/browser-narrow-with-filters.yaml +20 -0
- package/forgeqe.example.yaml +11 -1
- package/package.json +4 -1
- package/prompts/brain.md +4 -0
- package/prompts/browser-goal-verification.md +2 -0
- package/prompts/refine.md +2 -0
- package/prompts/requests-rule.md +1 -1
- package/prompts/talk-summary.md +43 -0
- package/prompts/talk.md +49 -0
- package/prompts/test-agent.md +1 -0
- package/prompts/test-reviewer.md +2 -1
- package/prompts/test-rules.md +3 -0
- package/py/forgeqe_data/__init__.py +1 -0
- package/py/forgeqe_data/__main__.py +12 -0
- package/py/forgeqe_data/connect.py +290 -0
- package/py/forgeqe_data/connstr.py +169 -0
- package/py/forgeqe_data/flows.py +603 -0
- package/py/forgeqe_data/guard.py +214 -0
- package/py/forgeqe_data/mongo.py +219 -0
- package/py/forgeqe_data/schema.py +431 -0
- package/py/forgeqe_data/service.py +651 -0
- package/py/forgeqe_data/streams.py +400 -0
- package/py/forgeqe_data/subset.py +299 -0
- package/py/forgeqe_data/testdata.py +861 -0
- package/py/forgeqe_data/vector.py +113 -0
- package/py/forgeqe_desktop/workflow.py +6 -4
- package/py/forgeqe_engine/capture.py +5 -4
- package/py/forgeqe_engine/diagnostics.py +2 -2
- package/py/forgeqe_engine/lenient_json.py +96 -0
- package/py/forgeqe_engine/llm.py +4 -0
- package/py/forgeqe_engine/network.py +93 -15
- package/py/forgeqe_engine/neutral_log.py +16 -1
- package/py/forgeqe_engine/recordsession.py +54 -1
- package/py/forgeqe_engine/service.py +22 -3
- package/py/forgeqe_mobile/appium_driver.py +9 -0
- package/py/forgeqe_mobile/apps.py +4 -0
- package/py/forgeqe_mobile/maestro.py +3 -0
- package/py/forgeqe_mobile/record.py +610 -0
- package/py/forgeqe_mobile/service.py +37 -7
- package/py/forgeqe_talk/__init__.py +1 -0
- package/py/forgeqe_talk/__main__.py +65 -0
- package/py/forgeqe_voice/worker.py +141 -0
- package/skills/dotnet-nunit-playwright/SKILL.md +1 -0
- package/skills/playwright-typescript/SKILL.md +1 -1
- package/dist/web/assets/Agent-DaA5WhAY.js +0 -8
- package/dist/web/assets/ApiTests-B7xsTGyo.js +0 -10
- package/dist/web/assets/Browse-ByYCyAwd.js +0 -2
- package/dist/web/assets/Chat-D1-cYNBr.js +0 -3
- package/dist/web/assets/CommandPalette-DbxKJJJB.js +0 -1
- package/dist/web/assets/Compare-CYLFEtJl.js +0 -1
- package/dist/web/assets/Cost-Csz0jMHo.js +0 -1
- package/dist/web/assets/Data-BWTme_Yw.js +0 -6
- package/dist/web/assets/Desktop-rZ0vB6Ie.js +0 -1
- package/dist/web/assets/DesktopReview-_Xha22_d.js +0 -1
- package/dist/web/assets/Evidence-DmUyZy9F.js +0 -1
- package/dist/web/assets/Explore-2wzgwz3J.js +0 -2
- package/dist/web/assets/Features-DazEWqYu.js +0 -1
- package/dist/web/assets/Flags-BTt0-pqd.js +0 -2
- package/dist/web/assets/Flaky-CjkQp73T.js +0 -1
- package/dist/web/assets/Impact-De87sv5J.js +0 -3
- package/dist/web/assets/Jobs-aiNGBVHL.js +0 -5
- package/dist/web/assets/KindPage-CrGoFeSa.js +0 -6
- package/dist/web/assets/Migration-BAhQ1DZO.js +0 -2
- package/dist/web/assets/Product-DpK-PIxV.js +0 -7
- package/dist/web/assets/Production-D6A89rZZ.js +0 -1
- package/dist/web/assets/Quality-Bc5wCsog.js +0 -1
- package/dist/web/assets/Readiness-CoVgZw2X.js +0 -1
- package/dist/web/assets/Record-DcgBatJJ.js +0 -2
- package/dist/web/assets/Regression-BJLYrqST.js +0 -5
- package/dist/web/assets/Reports-DYfyfEDy.js +0 -2
- package/dist/web/assets/Response-CNLi9Dqu.js +0 -4
- package/dist/web/assets/RunDiff-BMTdRhii.js +0 -1
- package/dist/web/assets/Runs-lb78rvPV.js +0 -2
- package/dist/web/assets/Steps-BDSeIznj.js +0 -2
- package/dist/web/assets/TestCases-CfUwd67O.js +0 -1
- package/dist/web/assets/TestData-DP7cvW48.js +0 -2
- package/dist/web/assets/TestDebt-CqARxL7k.js +0 -1
- package/dist/web/assets/Tosca-CLAz9tWT.js +0 -3
- package/dist/web/assets/WhatsNew-1lhTRE5Z.js +0 -1
- package/dist/web/assets/dataParts-DI_OJhy5.js +0 -3
- package/dist/web/assets/filters-CflRmNDz.js +0 -1
- package/dist/web/assets/fold-pOBiaSlF.js +0 -1
- package/dist/web/assets/frame-CYYiRu5P.js +0 -4
- package/dist/web/assets/index-CNDoTeRV.css +0 -2
- package/dist/web/assets/index-D4a0w3Vl.js +0 -67
- package/dist/web/assets/palette-Cj4CUs0K.js +0 -1
- package/dist/web/assets/parts-C53RxMcR.js +0 -1
- package/dist/web/assets/qualityParts-C9FItsTg.js +0 -1
- package/dist/web/assets/rows-D6rPRkHl.js +0 -1
- package/dist/web/assets/segmented-CAf_qz5Z.js +0 -1
- package/dist/web/assets/thread-DQdyL3Sv.js +0 -5
|
@@ -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)
|