modelcall 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 (57) hide show
  1. modelcall/__init__.py +3 -0
  2. modelcall/__main__.py +203 -0
  3. modelcall/agent.py +322 -0
  4. modelcall/agent_tools.py +465 -0
  5. modelcall/app.py +137 -0
  6. modelcall/batches.py +134 -0
  7. modelcall/checker.py +534 -0
  8. modelcall/cli.py +636 -0
  9. modelcall/doctor.py +113 -0
  10. modelcall/evaluator.py +174 -0
  11. modelcall/export.py +244 -0
  12. modelcall/inference.py +710 -0
  13. modelcall/matcher.py +276 -0
  14. modelcall/mcp_server.py +218 -0
  15. modelcall/migrate.py +120 -0
  16. modelcall/profiling.py +186 -0
  17. modelcall/providers/__init__.py +20 -0
  18. modelcall/providers/anthropic.py +223 -0
  19. modelcall/providers/base.py +89 -0
  20. modelcall/providers/fake.py +140 -0
  21. modelcall/providers/openai_compat.py +345 -0
  22. modelcall/resolver.py +303 -0
  23. modelcall/review.py +354 -0
  24. modelcall/schema.py +107 -0
  25. modelcall/serve.py +15 -0
  26. modelcall/settings.py +50 -0
  27. modelcall/sql/bridge/http.sql +53 -0
  28. modelcall/sql/bridge/plpython3u.sql +56 -0
  29. modelcall/sql/install.sql +26 -0
  30. modelcall/sql/migrations/0001_core.sql +589 -0
  31. modelcall/sql/migrations/0002_tasks.sql +941 -0
  32. modelcall/sql/migrations/0003_agent.sql +644 -0
  33. modelcall/sql/migrations/0004_master_data.sql +585 -0
  34. modelcall/sql/migrations/0005_mappings.sql +900 -0
  35. modelcall/sql/migrations/0006_providers.sql +32 -0
  36. modelcall/sql/migrations/0007_ledger.sql +735 -0
  37. modelcall/sql/migrations/0008_evaluation.sql +919 -0
  38. modelcall/sql/migrations/0009_semantics.sql +852 -0
  39. modelcall/sql/migrations/0010_conformance.sql +779 -0
  40. modelcall/sql/migrations/0011_standardization.sql +540 -0
  41. modelcall/sql/migrations/0012_entities.sql +686 -0
  42. modelcall/sql/migrations/0013_check_controls.sql +107 -0
  43. modelcall/sql/migrations/0014_preview_categories.sql +37 -0
  44. modelcall/sql/migrations/0015_agent_and_rules.sql +385 -0
  45. modelcall/sql/migrations/0016_check_population.sql +82 -0
  46. modelcall/sql/migrations/0017_rename_to_modelcall.sql +125 -0
  47. modelcall/sql/migrations/0018_routing.sql +260 -0
  48. modelcall/sql/migrations/0019_measured_routing.sql +207 -0
  49. modelcall/sql/migrations/0020_watch_costs_categories.sql +271 -0
  50. modelcall/text.py +45 -0
  51. modelcall/worker.py +307 -0
  52. modelcall-0.1.0.dist-info/METADATA +257 -0
  53. modelcall-0.1.0.dist-info/RECORD +57 -0
  54. modelcall-0.1.0.dist-info/WHEEL +5 -0
  55. modelcall-0.1.0.dist-info/entry_points.txt +2 -0
  56. modelcall-0.1.0.dist-info/licenses/LICENSE +202 -0
  57. modelcall-0.1.0.dist-info/top_level.txt +1 -0
modelcall/doctor.py ADDED
@@ -0,0 +1,113 @@
1
+ """`modelcall doctor`: checks that a database can run modelcall, before or after installing."""
2
+
3
+ import time
4
+
5
+ import psycopg
6
+
7
+ from .migrate import SQL_DIR, applied
8
+
9
+ OK, WARN, FAIL = "ok", "warn", "FAIL"
10
+
11
+
12
+ def run_checks(database_url: str) -> list[tuple[str, str, str]]:
13
+ results: list[tuple[str, str, str]] = []
14
+
15
+ def add(status: str, check: str, message: str) -> None:
16
+ results.append((status, check, message))
17
+
18
+ try:
19
+ conn = psycopg.connect(database_url, autocommit=True)
20
+ except psycopg.Error as exc:
21
+ add(FAIL, "connect", str(exc).strip())
22
+ return results
23
+
24
+ with conn:
25
+ one = lambda q, *p: conn.execute(q, p).fetchone()[0] # noqa: E731
26
+ version = one("SHOW server_version_num")
27
+ version = int(version)
28
+ if version < 150000:
29
+ add(FAIL, "version", f"PostgreSQL {version // 10000} found; modelcall needs 15 or later")
30
+ else:
31
+ add(OK, "version", f"PostgreSQL {version // 10000}")
32
+
33
+ encoding = one("SHOW server_encoding")
34
+ add(OK if encoding == "UTF8" else FAIL, "encoding",
35
+ "UTF8" if encoding == "UTF8" else f"{encoding}: master-data normalization needs a UTF8 database")
36
+
37
+ icu = one("SELECT EXISTS (SELECT FROM pg_collation WHERE collname = 'und-x-icu')")
38
+ add(OK if icu else WARN, "icu",
39
+ "ICU collations available" if icu
40
+ else "no ICU collations: normalization folds case with the database locale only")
41
+
42
+ user, superuser, createrole = conn.execute(
43
+ "SELECT current_user, rolsuper, rolcreaterole FROM pg_roles WHERE rolname = current_user").fetchone()
44
+ can_create = one("SELECT has_database_privilege(current_database(), 'CREATE')")
45
+ if superuser:
46
+ add(OK, "privileges", f"{user} is a superuser")
47
+ elif createrole and can_create:
48
+ add(OK, "privileges", f"{user} can create schemas and roles (enough for modelcall migrate)")
49
+ else:
50
+ missing = [x for x, have in (("CREATEROLE", createrole), ("CREATE on the database", can_create)) if not have]
51
+ add(WARN, "privileges", f"{user} lacks {' and '.join(missing)}: fine for running the engine, "
52
+ "but modelcall migrate needs them")
53
+
54
+ try:
55
+ done = applied(conn)
56
+ except psycopg.errors.InsufficientPrivilege:
57
+ add(WARN, "schema", f"{user} cannot read mod.migrations; run doctor as the installing role")
58
+ done = None
59
+ available = [p.stem for p in sorted((SQL_DIR / "migrations").glob("*.sql"))]
60
+ pending = [m for m in available if m not in done]
61
+ if done is None:
62
+ pass
63
+ elif not done:
64
+ add(WARN, "schema", "modelcall is not installed yet: run modelcall migrate")
65
+ elif pending:
66
+ add(WARN, "schema", f"pending migrations: {', '.join(pending)} (run modelcall migrate)")
67
+ else:
68
+ add(OK, "schema", f"installed, up to date ({available[-1]})")
69
+ member = one("SELECT pg_has_role(current_user, 'modelcall_engine', 'MEMBER')")
70
+ add(OK if member else WARN, "engine role",
71
+ f"{user} is a member of modelcall_engine" if member
72
+ else f"{user} is not a member of modelcall_engine: the engine should connect as a role that is "
73
+ "(GRANT modelcall_engine TO <engine login>)")
74
+
75
+ available = {r[0] for r in conn.execute(
76
+ "SELECT name FROM pg_available_extensions WHERE name IN ('plpython3u', 'http', 'pg_tle', 'vector')")}
77
+ if "plpython3u" in available:
78
+ add(OK, "sync bridge", "plpython3u available: modelcall install-bridge enables mod.classify and friends")
79
+ elif "http" in available:
80
+ add(OK, "sync bridge", "http extension available: modelcall install-bridge --kind http enables mod.classify "
81
+ "and friends")
82
+ else:
83
+ add(OK, "sync bridge", "neither plpython3u nor http available (usual on managed Postgres): use modelcall check, "
84
+ "tasks, the agent, master data and mappings; the synchronous functions raise a clear error")
85
+ if "pg_tle" in available:
86
+ add(OK, "pg_tle", "pg_tle available: modelcall can also be installed as an extension (modelcall package)")
87
+ add(OK, "pgvector", "pgvector installed: large code sets are ranked in SQL" if one(
88
+ "SELECT EXISTS (SELECT FROM pg_extension WHERE extname = 'vector')")
89
+ else "pgvector not installed: large code sets with an embedding model are ranked in the engine")
90
+
91
+ # The worker waits on LISTEN/NOTIFY; transaction-pooling proxies drop notifications.
92
+ try:
93
+ conn.execute("LISTEN modelcall_doctor")
94
+ conn.execute("NOTIFY modelcall_doctor, 'ping'")
95
+ deadline = time.time() + 2
96
+ received = False
97
+ while time.time() < deadline and not received:
98
+ received = any(True for _ in conn.notifies(timeout=0.5, stop_after=1))
99
+ add(OK if received else WARN, "notify",
100
+ "LISTEN/NOTIFY works" if received
101
+ else "no notification came back: if you connect through a transaction-pooling proxy, give the "
102
+ "engine a direct (or session-pooled) connection; workers still poll, just later")
103
+ except psycopg.Error as exc:
104
+ add(WARN, "notify", f"LISTEN failed: {exc}")
105
+ return results
106
+
107
+
108
+ def main(database_url: str) -> int:
109
+ results = run_checks(database_url)
110
+ width = max(len(c) for _, c, _ in results)
111
+ for status, check, message in results:
112
+ print(f"[{status:>4}] {check:<{width}} {message}")
113
+ return 1 if any(status == FAIL for status, _, _ in results) else 0
modelcall/evaluator.py ADDED
@@ -0,0 +1,174 @@
1
+ """The evaluation runner: works through runs queued by mod.evaluate.
2
+
3
+ A run is one subject's examples (a task, a master-data domain or a checked
4
+ column) against one model profile. Every example goes through the same code
5
+ path as production (Engine.run for tasks, the resolver's decide for domains,
6
+ the checker's judge for columns), so evaluation calls are cached, recorded in
7
+ mod.calls and priced like any other. Results are compared with the expected
8
+ answers here and summarised by mod._eval_finish.
9
+ """
10
+
11
+ import asyncio
12
+ import logging
13
+ import os
14
+ import socket
15
+ from typing import Any, Optional
16
+
17
+ import psycopg
18
+ from psycopg.rows import dict_row
19
+ from psycopg.types.json import Jsonb
20
+
21
+ from .agent import _sleep_unless, _wait_for_notify
22
+ from .inference import Engine, RequestError
23
+ from .text import fold
24
+
25
+ log = logging.getLogger("modelcall.evaluator")
26
+
27
+ CHANNEL = "modelcall_eval"
28
+ CHUNK = 200
29
+
30
+
31
+ def same(a: Any, b: Any) -> bool:
32
+ """Equality of a result and an expected answer: strings compare folded
33
+ (case, accents, punctuation), numbers by value, objects field by field."""
34
+ if isinstance(a, str) and isinstance(b, str):
35
+ return a == b or fold(a) == fold(b)
36
+ if isinstance(a, bool) or isinstance(b, bool):
37
+ return a is b
38
+ if isinstance(a, (int, float)) and isinstance(b, (int, float)):
39
+ return abs(a - b) <= 1e-9 * max(1.0, abs(a), abs(b))
40
+ if isinstance(a, dict) and isinstance(b, dict):
41
+ return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a)
42
+ if isinstance(a, list) and isinstance(b, list):
43
+ return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
44
+ return a == b
45
+
46
+
47
+ class EvalRunner:
48
+ def __init__(self, engine: Engine, name: Optional[str] = None):
49
+ from .checker import Checker
50
+ from .resolver import Resolver
51
+
52
+ settings = engine.settings
53
+ self.engine = engine
54
+ self.name = name or f"{socket.gethostname()}:{os.getpid()}:eval"
55
+ self.lease_seconds = settings.worker_lease_seconds
56
+ self.poll_seconds = settings.worker_poll_seconds
57
+ self.resolver = Resolver(engine, name=self.name)
58
+ self.checker = Checker(engine, name=self.name)
59
+
60
+ async def run_once(self) -> bool:
61
+ async with self.engine.pool.connection() as conn:
62
+ cur = conn.cursor(row_factory=dict_row)
63
+ await cur.execute("SELECT * FROM mod.claim_eval_run(make_interval(secs => %s), %s)",
64
+ (self.lease_seconds, self.name))
65
+ run = await cur.fetchone()
66
+ if run is None:
67
+ return False
68
+ try:
69
+ await self._process(run)
70
+ except psycopg.errors.LockNotAvailable:
71
+ log.warning("eval run %s: lease lost", run["id"])
72
+ except Exception as exc:
73
+ log.exception("eval run %s failed", run["id"])
74
+ await self._finish(run, f"{type(exc).__name__}: {exc}")
75
+ return True
76
+
77
+ async def drain(self) -> int:
78
+ count = 0
79
+ while await self.run_once():
80
+ count += 1
81
+ return count
82
+
83
+ async def run(self, stop: Optional[asyncio.Event] = None) -> None:
84
+ stop = stop or asyncio.Event()
85
+ listener: Optional[psycopg.AsyncConnection] = None
86
+ while not stop.is_set():
87
+ try:
88
+ if listener is None or listener.closed:
89
+ listener = await psycopg.AsyncConnection.connect(self.engine.settings.database_url, autocommit=True)
90
+ await listener.execute(f"LISTEN {CHANNEL}")
91
+ if await self.run_once():
92
+ continue
93
+ await _wait_for_notify(listener, stop, self.poll_seconds)
94
+ except asyncio.CancelledError:
95
+ raise
96
+ except Exception:
97
+ log.exception("evaluation round failed; retrying in %ss", self.poll_seconds)
98
+ if listener is not None:
99
+ await listener.close()
100
+ listener = None
101
+ await _sleep_unless(stop, self.poll_seconds)
102
+ if listener is not None:
103
+ await listener.close()
104
+
105
+ async def _finish(self, run: dict, error: Optional[str] = None) -> None:
106
+ async with self.engine.pool.connection() as conn:
107
+ await conn.execute("SELECT mod._eval_finish(%s, %s, %s)", (run["id"], run["lease_token"], error))
108
+
109
+ async def _process(self, run: dict) -> None:
110
+ pending = await self.engine._fetchall(
111
+ """SELECT example_id, input, expected FROM mod.eval_results
112
+ WHERE run_id = %s AND status IS NULL ORDER BY example_id""", run["id"])
113
+ for start in range(0, len(pending), CHUNK):
114
+ chunk = pending[start:start + CHUNK]
115
+ try:
116
+ results = await self._evaluate(run, chunk)
117
+ except RequestError as exc:
118
+ await self._finish(run, exc.message)
119
+ return
120
+ async with self.engine.pool.connection() as conn:
121
+ await conn.execute("SELECT mod._eval_record(%s, %s, %s)",
122
+ (run["id"], run["lease_token"], Jsonb(results)))
123
+ await self._finish(run)
124
+
125
+ async def _evaluate(self, run: dict, rows: list[dict]) -> list[dict]:
126
+ source = f"eval:{run['id']}"
127
+ if run["kind"] == "task":
128
+ spec = await self.engine.load_task(run["subject"], run["task_version"])
129
+ results = await self.engine.run(spec, [r["input"] for r in rows], model=run["model"],
130
+ caller=f"eval:{self.name}", source=source)
131
+ out = []
132
+ for row, result in zip(rows, results):
133
+ expected = row["expected"]
134
+ got = result.output if result.status == "ok" else None
135
+ if expected is None:
136
+ correct = result.status == "abstain" or (result.status == "ok" and got is None)
137
+ else:
138
+ correct = result.status == "ok" and same(got, expected)
139
+ out.append(_row(row, result.status, got, correct, result.call_id, result.error))
140
+ return out
141
+
142
+ if run["kind"] == "domain":
143
+ info, codes = await self.resolver.load_domain(run["subject"])
144
+ decided = await asyncio.gather(*(
145
+ self.resolver.decide(info, codes, r["input"].get("value") or "", r["input"].get("context") or None,
146
+ model=run["model"], source=source) for r in rows))
147
+ out = []
148
+ for row, d in zip(rows, decided):
149
+ got = d.get("key") if d["status"] == "ok" else None
150
+ expected = row["expected"]
151
+ status = d["status"]
152
+ correct = status in ("ok", "abstain") and (got == expected if expected is not None else got is None)
153
+ out.append(_row(row, status, got, correct, d.get("call_id"), d.get("error") or d.get("reason")))
154
+ return out
155
+
156
+ if run["kind"] == "column":
157
+ values = [{"value": r["input"].get("value"), "context": r["input"].get("context")} for r in rows]
158
+ verdicts = await self.checker.judge_examples(run["subject"], values, run["model"], source)
159
+ out = []
160
+ for row, v in zip(rows, verdicts):
161
+ if v["status"] != "ok":
162
+ out.append(_row(row, v["status"], None, False, v.get("call_id"), v.get("error")))
163
+ continue
164
+ got = {"verdict": v["verdict"], "category": v.get("category")}
165
+ status = "abstain" if v["verdict"] == "unsure" else "ok"
166
+ correct = v["verdict"] == row["expected"].get("verdict")
167
+ out.append(_row(row, status, got, correct, v.get("call_id"), v.get("rationale")))
168
+ return out
169
+ raise RequestError(400, "config_error", f"unknown subject kind {run['kind']!r}")
170
+
171
+
172
+ def _row(row: dict, status: str, got: Any, correct: bool, call_id: Optional[int], detail: Optional[str]) -> dict:
173
+ return {"example_id": row["example_id"], "status": status, "got": got, "correct": bool(correct),
174
+ "call_id": call_id, "detail": None if correct else detail}
modelcall/export.py ADDED
@@ -0,0 +1,244 @@
1
+ """Exports of governed metadata: dbt schema.yml, SQL migration files, JSON.
2
+
3
+ * `sql` without --run: COMMENT ON statements for every recorded definition,
4
+ for teams that review metadata through pull requests.
5
+ * `sql --run N` (or --approved): the approved proposals as a migration file.
6
+ Comments are written as COMMENT ON statements followed by
7
+ mod.mark_applied(id), so edits made in review are what gets recorded; other
8
+ kinds call mod.apply(id), with the statement they run shown above it.
9
+ * `dbt`: schema.yml with descriptions and tests from mod.rules and
10
+ mod.relationships, plus the generic test behind conformance rules.
11
+ * `json`: semantics, rules, relationships, transforms and mappings.
12
+ """
13
+
14
+ import json
15
+ import textwrap
16
+ from datetime import datetime, timezone
17
+ from typing import Any, Optional
18
+
19
+ import psycopg
20
+ from psycopg import sql
21
+ from psycopg.rows import dict_row
22
+
23
+ CONFORMANCE_TEST = """\
24
+ {% test modelcall_conformance(model, column_name, threshold=0.95) %}
25
+ {#- Fails when the share of rows conforming to the column's definition (mod.conformance) is below threshold,
26
+ or when the column has not been checked. Generated by `modelcall export --format dbt`. -#}
27
+ with c as (
28
+ select conform_pct
29
+ from mod.conformance
30
+ where column_name = '{{ model.schema }}.{{ model.identifier }}.{{ column_name }}'
31
+ )
32
+ select 'not checked' as problem where not exists (select 1 from c)
33
+ union all
34
+ select 'conform_pct ' || conform_pct::text from c where coalesce(conform_pct, 0) / 100 < {{ threshold }}
35
+ {% endtest %}
36
+ """
37
+
38
+
39
+ def _rows(conn: psycopg.Connection, query: Any, params: Any = None) -> list[dict]:
40
+ return conn.cursor(row_factory=dict_row).execute(query, params).fetchall()
41
+
42
+
43
+ def _sql_comment(text: Optional[str], prefix: str = "-- ") -> str:
44
+ if not text:
45
+ return ""
46
+ lines = []
47
+ for paragraph in str(text).splitlines() or [""]:
48
+ lines.extend(textwrap.wrap(paragraph, 100) or [""])
49
+ return "\n".join(prefix + line for line in lines) + "\n"
50
+
51
+
52
+ def _header(title: str) -> str:
53
+ stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
54
+ return f"-- {title}\n-- Generated by `modelcall export` on {stamp}. Review it like any other migration.\n\n"
55
+
56
+
57
+ def semantics(conn: psycopg.Connection, schemas: Optional[list[str]] = None) -> list[dict]:
58
+ return _rows(conn, """
59
+ SELECT s.schema_name, s.table_name, s.column_name, s.definition, s.synonyms, s.unit, s.value_format,
60
+ s.examples, s.sensitivity, s.categories, s.version, c.relkind
61
+ FROM mod.semantics s
62
+ LEFT JOIN pg_class c ON c.oid = to_regclass(format('%%I.%%I', s.schema_name, s.table_name))
63
+ WHERE (%(schemas)s::text[] IS NULL OR s.schema_name = ANY (%(schemas)s))
64
+ AND mod.policy_level(s.schema_name, s.table_name, s.column_name) <> 'deny'
65
+ ORDER BY s.schema_name, s.table_name, s.column_name NULLS FIRST""", {"schemas": schemas})
66
+
67
+
68
+ def export_sql_semantics(conn: psycopg.Connection, schemas: Optional[list[str]] = None) -> str:
69
+ out = [_header("Definitions recorded in mod.semantics, as COMMENT ON statements")]
70
+ for s in semantics(conn, schemas):
71
+ if not s["definition"]:
72
+ continue
73
+ if s["column_name"] is None:
74
+ kind = {"v": "VIEW", "m": "MATERIALIZED VIEW", "f": "FOREIGN TABLE"}.get(s["relkind"], "TABLE")
75
+ stmt = sql.SQL("COMMENT ON {} {} IS {};").format(
76
+ sql.SQL(kind), sql.Identifier(s["schema_name"], s["table_name"]), sql.Literal(s["definition"]))
77
+ else:
78
+ stmt = sql.SQL("COMMENT ON COLUMN {} IS {};").format(
79
+ sql.Identifier(s["schema_name"], s["table_name"], s["column_name"]), sql.Literal(s["definition"]))
80
+ out.append(stmt.as_string(conn) + "\n")
81
+ return "".join(out)
82
+
83
+
84
+ def export_sql_proposals(conn: psycopg.Connection, run: Optional[int] = None) -> str:
85
+ rows = _rows(conn, """SELECT id, kind, target, rationale, run_id FROM mod.proposals
86
+ WHERE status = 'approved' AND (%(run)s::bigint IS NULL OR run_id = %(run)s)
87
+ ORDER BY id""", {"run": run})
88
+ title = f"Approved proposals of agent run {run}" if run else "Approved proposals"
89
+ out = [_header(title), "BEGIN;\n\n"]
90
+ if not rows:
91
+ out.append("-- Nothing approved and pending.\n")
92
+ for p in rows:
93
+ preview = conn.execute("SELECT mod.preview(%s)", (p["id"],)).fetchone()[0]
94
+ out.append(f"-- #{p['id']} {p['kind']}: {p['target']}\n")
95
+ out.append(_sql_comment(p["rationale"], "-- why: "))
96
+ if preview.get("flags"):
97
+ out.append(f"-- FLAGGED: {', '.join(preview['flags'])} (text that looks like instructions)\n")
98
+ if preview.get("stale"):
99
+ out.append("-- STALE: the object changed after this was proposed\n")
100
+ if p["kind"] == "comment" and preview.get("sql"):
101
+ out.append(preview["sql"] + ";\n")
102
+ out.append(f"SELECT mod.mark_applied({p['id']});\n\n")
103
+ else:
104
+ if preview.get("sql"):
105
+ out.append(_sql_comment(preview["sql"], "-- runs: "))
106
+ out.append(f"SELECT mod.apply({p['id']});\n\n")
107
+ out.append("COMMIT;\n")
108
+ return "".join(out)
109
+
110
+
111
+ def _yaml_scalar(value: Any) -> str:
112
+ if value is None:
113
+ return "null"
114
+ if isinstance(value, bool):
115
+ return "true" if value else "false"
116
+ if isinstance(value, (int, float)):
117
+ return json.dumps(value)
118
+ return json.dumps(str(value), ensure_ascii=False) # JSON strings are valid YAML double-quoted scalars
119
+
120
+
121
+ def _yaml(value: Any, indent: int = 0) -> list[str]:
122
+ pad = " " * indent
123
+ lines: list[str] = []
124
+ if isinstance(value, dict):
125
+ for k, v in value.items():
126
+ if isinstance(v, (dict, list)) and v:
127
+ lines.append(f"{pad}{k}:")
128
+ lines.extend(_yaml(v, indent + 2))
129
+ else:
130
+ lines.append(f"{pad}{k}: {_yaml_scalar(v) if not isinstance(v, (dict, list)) else ('{}' if isinstance(v, dict) else '[]')}")
131
+ elif isinstance(value, list):
132
+ for item in value:
133
+ if isinstance(item, dict) and item:
134
+ first, *rest = _yaml(item, indent + 2)
135
+ lines.append(f"{pad}- {first.strip()}")
136
+ lines.extend(rest)
137
+ elif isinstance(item, list):
138
+ lines.append(f"{pad}- " + json.dumps(item, ensure_ascii=False))
139
+ else:
140
+ lines.append(f"{pad}- {_yaml_scalar(item)}")
141
+ return lines
142
+
143
+
144
+ def _dbt_test(rule: dict) -> Any:
145
+ params = rule["params"] or {}
146
+ if rule["rule"] in ("not_null", "unique"):
147
+ test: Any = rule["rule"]
148
+ elif rule["rule"] == "accepted_values":
149
+ test = {"accepted_values": {"values": params.get("values", [])}}
150
+ elif rule["rule"] == "range":
151
+ bounds = {k: params[src] for k, src in (("min_value", "min"), ("max_value", "max")) if src in params}
152
+ test = {"dbt_utils.accepted_range": bounds}
153
+ else:
154
+ test = {"modelcall_conformance": {"threshold": params.get("threshold", 0.95)}}
155
+ if rule["severity"] == "warn":
156
+ if isinstance(test, str):
157
+ test = {test: {"config": {"severity": "warn"}}}
158
+ else:
159
+ next(iter(test.values()))["config"] = {"severity": "warn"}
160
+ return test
161
+
162
+
163
+ def export_dbt(conn: psycopg.Connection, schemas: Optional[list[str]] = None, as_sources: bool = False) -> str:
164
+ sems = semantics(conn, schemas)
165
+ rules = _rows(conn, """SELECT * FROM mod.rules WHERE %(schemas)s::text[] IS NULL OR schema_name = ANY (%(schemas)s)
166
+ ORDER BY name""", {"schemas": schemas})
167
+ rels = _rows(conn, "SELECT * FROM mod.relationships ORDER BY id")
168
+ tables: dict[tuple[str, str], dict] = {}
169
+
170
+ def table(schema: str, name: str) -> dict:
171
+ return tables.setdefault((schema, name), {"name": name, "description": None, "columns": {}})
172
+
173
+ def column(schema: str, name: str, col: str) -> dict:
174
+ return table(schema, name)["columns"].setdefault(col, {"name": col, "description": None, "data_tests": []})
175
+
176
+ for s in sems:
177
+ if s["column_name"] is None:
178
+ table(s["schema_name"], s["table_name"])["description"] = s["definition"]
179
+ else:
180
+ c = column(s["schema_name"], s["table_name"], s["column_name"])
181
+ c["description"] = s["definition"]
182
+ meta = {k: s[k] for k in ("unit", "value_format", "sensitivity") if s[k]}
183
+ if s["synonyms"]:
184
+ meta["synonyms"] = s["synonyms"]
185
+ if meta:
186
+ c["meta"] = meta
187
+ for r in rules:
188
+ column(r["schema_name"], r["table_name"], r["column_name"])["data_tests"].append(_dbt_test(r))
189
+ for rel in rels:
190
+ src_schema, src_table = rel["from_relation"].replace('"', "").split(".", 1)
191
+ if schemas and src_schema not in schemas:
192
+ continue
193
+ to_schema, to_table = rel["to_relation"].replace('"', "").split(".", 1)
194
+ if len(rel["from_columns"]) != 1:
195
+ continue # dbt's relationships test takes one column
196
+ target = f"source('{to_schema}', '{to_table}')" if as_sources else f"ref('{to_table}')"
197
+ column(src_schema, src_table, rel["from_columns"][0])["data_tests"].append(
198
+ {"relationships": {"to": target, "field": rel["to_columns"][0]}})
199
+
200
+ def clean_table(t: dict) -> dict:
201
+ out: dict = {"name": t["name"]}
202
+ if t["description"]:
203
+ out["description"] = t["description"]
204
+ cols = []
205
+ for c in t["columns"].values():
206
+ entry: dict = {"name": c["name"]}
207
+ if c["description"]:
208
+ entry["description"] = c["description"]
209
+ if c.get("meta"):
210
+ entry["meta"] = c["meta"]
211
+ if c["data_tests"]:
212
+ entry["data_tests"] = c["data_tests"]
213
+ cols.append(entry)
214
+ if cols:
215
+ out["columns"] = cols
216
+ return out
217
+
218
+ if as_sources:
219
+ by_schema: dict[str, list] = {}
220
+ for (schema, _), t in sorted(tables.items()):
221
+ by_schema.setdefault(schema, []).append(clean_table(t))
222
+ doc: dict = {"version": 2, "sources": [{"name": s, "schema": s, "tables": ts} for s, ts in by_schema.items()]}
223
+ else:
224
+ doc = {"version": 2, "models": [clean_table(t) for _, t in sorted(tables.items())]}
225
+ return "# Generated by `modelcall export --format dbt` from mod.semantics, mod.rules and mod.relationships.\n" \
226
+ + "\n".join(_yaml(doc)) + "\n"
227
+
228
+
229
+ def export_json(conn: psycopg.Connection, schemas: Optional[list[str]] = None) -> str:
230
+ def j(rows: list[dict]) -> list[dict]:
231
+ return json.loads(json.dumps(rows, default=str))
232
+
233
+ data = {
234
+ "semantics": j([{k: v for k, v in s.items() if k != "relkind"} for s in semantics(conn, schemas)]),
235
+ "rules": j(_rows(conn, """SELECT name, schema_name, table_name, column_name, rule, params, severity, description
236
+ FROM mod.rules WHERE %(s)s::text[] IS NULL OR schema_name = ANY (%(s)s) ORDER BY name""",
237
+ {"s": schemas})),
238
+ "relationships": j(_rows(conn, "SELECT from_relation, from_columns, to_relation, to_columns, orphans, "
239
+ "constraint_name FROM mod.relationships ORDER BY id")),
240
+ "transforms": j(_rows(conn, "SELECT name, description, expression, output_type, version FROM mod.transforms "
241
+ "ORDER BY name")),
242
+ "mappings": j(_rows(conn, "SELECT name, target, mode, version, spec FROM mod.mappings ORDER BY name")),
243
+ }
244
+ return json.dumps(data, indent=2, ensure_ascii=False) + "\n"