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
@@ -0,0 +1,540 @@
1
+ -- ============================================================================
2
+ -- modelcall 1.0 mapping and standardization (design-v1 sections 6 and 9).
3
+ --
4
+ -- * Large code sets: a domain may name an embedding model; the resolver then
5
+ -- ranks candidates by embedding similarity (pgvector when installed) and
6
+ -- stores the code embeddings in mod.code_embeddings.
7
+ -- * Pattern standardization: a 'transform' proposal is an expression over
8
+ -- "$value" in the mapping compiler's whitelist. Its preview runs it on real
9
+ -- values and counts failures; applied transforms are used in mappings as
10
+ -- {"transform": "name", "value": <expr>} and ad hoc with mod.transform().
11
+ -- * Mappings: delete propagation (delete_missing, delete_scope) and
12
+ -- watermark-based incremental reads (incremental: {"expr": <expr>}).
13
+ -- ============================================================================
14
+
15
+ -- ----------------------------------------------------------------------------
16
+ -- Embeddings for large code sets
17
+ -- ----------------------------------------------------------------------------
18
+ ALTER TABLE mod.domains
19
+ ADD COLUMN embedding_model text REFERENCES mod.models (name),
20
+ ADD COLUMN embed_threshold int NOT NULL DEFAULT 1000 CHECK (embed_threshold > 0);
21
+ COMMENT ON COLUMN mod.domains.embedding_model IS 'Model profile with embeddings (provider openai or fake); used to rank candidates in large code sets';
22
+ COMMENT ON COLUMN mod.domains.embed_threshold IS 'Code sets larger than this are ranked by embeddings when embedding_model is set';
23
+
24
+ CREATE TABLE mod.code_embeddings (
25
+ domain text NOT NULL REFERENCES mod.domains ON DELETE CASCADE ON UPDATE CASCADE,
26
+ key text NOT NULL,
27
+ text_hash text NOT NULL,
28
+ embedding real[] NOT NULL,
29
+ model text NOT NULL,
30
+ updated_at timestamptz NOT NULL DEFAULT now(),
31
+ PRIMARY KEY (domain, key)
32
+ );
33
+ COMMENT ON TABLE mod.code_embeddings IS 'Embeddings of code labels and aliases, kept in step with the code set by the resolver';
34
+
35
+ DROP FUNCTION mod.create_domain(text, regclass, text, text, text[], text, text, boolean);
36
+ CREATE FUNCTION mod.create_domain(
37
+ name text,
38
+ target regclass,
39
+ key text,
40
+ label text DEFAULT NULL,
41
+ aliases text[] DEFAULT '{}',
42
+ description text DEFAULT NULL,
43
+ model text DEFAULT NULL,
44
+ auto_accept boolean DEFAULT false,
45
+ embedding_model text DEFAULT NULL,
46
+ embed_threshold int DEFAULT 1000
47
+ ) RETURNS void
48
+ LANGUAGE plpgsql AS $$
49
+ DECLARE
50
+ col text;
51
+ key_num int2;
52
+ BEGIN
53
+ FOREACH col IN ARRAY ARRAY[key, label] || coalesce(aliases, '{}') LOOP
54
+ CONTINUE WHEN col IS NULL;
55
+ IF NOT EXISTS (SELECT FROM pg_attribute a WHERE a.attrelid = target AND a.attname = col
56
+ AND a.attnum > 0 AND NOT a.attisdropped) THEN
57
+ RAISE EXCEPTION 'mod.create_domain: % has no column %', target, col;
58
+ END IF;
59
+ END LOOP;
60
+ SELECT a.attnum INTO key_num FROM pg_attribute a WHERE a.attrelid = target AND a.attname = key;
61
+ IF NOT EXISTS (SELECT FROM pg_index i WHERE i.indrelid = target AND i.indisunique
62
+ AND i.indnkeyatts = 1 AND i.indkey[0] = key_num AND i.indpred IS NULL) THEN
63
+ RAISE EXCEPTION 'mod.create_domain: % must be unique in % (a primary key or unique constraint)', key, target;
64
+ END IF;
65
+
66
+ INSERT INTO mod.domains (name, target, key_column, label_column, alias_columns, description, model, auto_accept,
67
+ embedding_model, embed_threshold)
68
+ VALUES (name, target, key, label, coalesce(aliases, '{}'), description, model, auto_accept,
69
+ embedding_model, coalesce(embed_threshold, 1000))
70
+ ON CONFLICT ON CONSTRAINT domains_pkey DO UPDATE
71
+ SET target = EXCLUDED.target, key_column = EXCLUDED.key_column, label_column = EXCLUDED.label_column,
72
+ alias_columns = EXCLUDED.alias_columns, description = EXCLUDED.description,
73
+ model = EXCLUDED.model, auto_accept = EXCLUDED.auto_accept,
74
+ embedding_model = EXCLUDED.embedding_model, embed_threshold = EXCLUDED.embed_threshold;
75
+ -- The resolver reads the code set to rank candidates.
76
+ EXECUTE format('GRANT SELECT ON %s TO modelcall_engine', target);
77
+ END $$;
78
+
79
+ -- ----------------------------------------------------------------------------
80
+ -- Transforms
81
+ -- ----------------------------------------------------------------------------
82
+ CREATE TYPE mod.transform_input AS (value text);
83
+
84
+ CREATE TABLE mod.transforms (
85
+ name text PRIMARY KEY CHECK (name ~ '^[a-z][a-z0-9_]*$'),
86
+ description text,
87
+ expression jsonb NOT NULL,
88
+ output_type text,
89
+ sample_column text,
90
+ version int NOT NULL DEFAULT 1,
91
+ proposal_id bigint REFERENCES mod.proposals ON DELETE SET NULL,
92
+ updated_at timestamptz NOT NULL DEFAULT now(),
93
+ updated_by text NOT NULL DEFAULT session_user
94
+ );
95
+ COMMENT ON TABLE mod.transforms IS 'Approved standardization rules: a mapping expression over "$value", run as plain SQL';
96
+
97
+ -- Replaces every string node equal to `needle` with `replacement`.
98
+ CREATE FUNCTION mod._substitute(e jsonb, needle text, replacement jsonb) RETURNS jsonb
99
+ LANGUAGE sql IMMUTABLE AS $$
100
+ SELECT CASE jsonb_typeof(e)
101
+ WHEN 'string' THEN CASE WHEN e #>> '{}' = needle THEN replacement ELSE e END
102
+ WHEN 'array' THEN coalesce((SELECT jsonb_agg(mod._substitute(x, needle, replacement) ORDER BY i)
103
+ FROM jsonb_array_elements(e) WITH ORDINALITY u(x, i)), '[]'::jsonb)
104
+ WHEN 'object' THEN coalesce((SELECT jsonb_object_agg(k, CASE WHEN k = 'value' AND jsonb_typeof(v) <> 'object'
105
+ AND e ?| ARRAY['resolve', 'transform'] = false
106
+ THEN v -- {"value": literal} stays literal
107
+ ELSE mod._substitute(v, needle, replacement) END)
108
+ FROM jsonb_each(e) x(k, v)), '{}'::jsonb)
109
+ ELSE e END;
110
+ $$;
111
+
112
+ -- Replaces {"transform": name, "value": <expr>} nodes with the stored expressions.
113
+ CREATE FUNCTION mod._expand_transforms(e jsonb, depth int DEFAULT 0) RETURNS jsonb
114
+ LANGUAGE plpgsql STABLE AS $$
115
+ DECLARE
116
+ t mod.transforms;
117
+ BEGIN
118
+ IF depth > 10 THEN
119
+ RAISE EXCEPTION 'mapping: transforms nest too deeply';
120
+ END IF;
121
+ IF jsonb_typeof(e) = 'object' AND e ? 'transform' THEN
122
+ SELECT * INTO t FROM mod.transforms x WHERE x.name = e ->> 'transform';
123
+ IF NOT FOUND THEN
124
+ RAISE EXCEPTION 'mapping: unknown transform %', e ->> 'transform';
125
+ END IF;
126
+ IF NOT e ? 'value' THEN
127
+ RAISE EXCEPTION 'mapping: transform % needs value', e ->> 'transform';
128
+ END IF;
129
+ RETURN mod._expand_transforms(mod._substitute(t.expression, '$value', mod._expand_transforms(e -> 'value', depth + 1)),
130
+ depth + 1);
131
+ ELSIF jsonb_typeof(e) = 'object' THEN
132
+ RETURN (SELECT jsonb_object_agg(k, mod._expand_transforms(v, depth)) FROM jsonb_each(e) x(k, v));
133
+ ELSIF jsonb_typeof(e) = 'array' THEN
134
+ RETURN coalesce((SELECT jsonb_agg(mod._expand_transforms(x, depth) ORDER BY i)
135
+ FROM jsonb_array_elements(e) WITH ORDINALITY u(x, i)), '[]'::jsonb);
136
+ END IF;
137
+ RETURN e;
138
+ END $$;
139
+
140
+ -- The SQL of an expression over "$value", reading the column `ref` (alias.column) of `rels`.
141
+ CREATE FUNCTION mod._compile_transform(expression jsonb, rels jsonb, ref text, mode text) RETURNS text
142
+ LANGUAGE plpgsql STABLE AS $$
143
+ BEGIN
144
+ IF jsonb_typeof(expression) IS DISTINCT FROM 'object' AND jsonb_typeof(expression) IS DISTINCT FROM 'string' THEN
145
+ RAISE EXCEPTION 'transform: expression must be a mapping expression over "$value"';
146
+ END IF;
147
+ IF position('"$value"' IN expression::text) = 0 THEN
148
+ RAISE EXCEPTION 'transform: the expression never uses "$value"';
149
+ END IF;
150
+ RETURN mod._compile_expr(mod._expand_transforms(mod._substitute(expression, '$value', to_jsonb(ref))), rels, mode);
151
+ END $$;
152
+
153
+ -- Runs a transform expression on real values of a column: before and after,
154
+ -- with failures (NULL results, or values not valid for output_type) counted.
155
+ CREATE FUNCTION mod.check_transform(expression jsonb, column_name text, output_type text DEFAULT NULL,
156
+ sample int DEFAULT 200) RETURNS jsonb
157
+ LANGUAGE plpgsql AS $$
158
+ DECLARE
159
+ col text;
160
+ parts text[];
161
+ rel regclass;
162
+ expr_sql text;
163
+ typ regtype;
164
+ res jsonb;
165
+ BEGIN
166
+ BEGIN
167
+ col := mod._column_name(column_name);
168
+ parts := parse_ident(col);
169
+ rel := to_regclass(format('%I.%I', parts[1], parts[2]));
170
+ expr_sql := mod._compile_transform(expression, jsonb_build_object('t', rel::oid), 't.' || parts[3], 'check');
171
+ IF output_type IS NOT NULL THEN
172
+ typ := to_regtype(output_type);
173
+ IF typ IS NULL THEN
174
+ RAISE EXCEPTION 'transform: unknown type %', output_type;
175
+ END IF;
176
+ END IF;
177
+ EXCEPTION WHEN OTHERS THEN
178
+ RETURN jsonb_build_object('ok', false, 'error', SQLERRM);
179
+ END;
180
+ EXECUTE format($q$
181
+ WITH r AS (SELECT (t.%1$I)::text AS before, (%4$s)::text AS after
182
+ FROM (SELECT DISTINCT %1$I FROM %2$s WHERE %1$I IS NOT NULL LIMIT %3$s) AS t),
183
+ f AS (SELECT r.*, (r.after IS NULL %5$s) AS failed FROM r)
184
+ SELECT jsonb_build_object(
185
+ 'checked', count(*),
186
+ 'changed', count(*) FILTER (WHERE NOT failed AND after IS DISTINCT FROM before),
187
+ 'unchanged', count(*) FILTER (WHERE NOT failed AND after = before),
188
+ 'failures', count(*) FILTER (WHERE failed),
189
+ 'examples', coalesce((jsonb_agg(jsonb_build_object('before', before, 'after', after))
190
+ FILTER (WHERE NOT failed AND after IS DISTINCT FROM before)) -> 0, 'null'::jsonb),
191
+ 'changed_examples', coalesce(jsonb_path_query_array(
192
+ jsonb_agg(jsonb_build_object('before', before, 'after', after)) FILTER (WHERE NOT failed AND after IS DISTINCT FROM before),
193
+ '$[0 to 9]'), '[]'),
194
+ 'failure_examples', coalesce(jsonb_path_query_array(
195
+ jsonb_agg(before) FILTER (WHERE failed), '$[0 to 9]'), '[]'))
196
+ FROM f
197
+ $q$, parts[3], rel, greatest(1, least(sample, 10000)), expr_sql,
198
+ CASE WHEN typ IS NOT NULL THEN format('OR NOT %s(r.after, %L)', mod._input_check_fn(), format_type(typ, NULL)) ELSE '' END)
199
+ INTO res;
200
+ RETURN res - 'examples' || jsonb_build_object('ok', (res ->> 'failures')::int = 0, 'column', col, 'sql', expr_sql);
201
+ END $$;
202
+
203
+ -- Applies an approved transform to one value (ad hoc use, views).
204
+ CREATE FUNCTION mod.transform(name text, value text) RETURNS text
205
+ LANGUAGE plpgsql STABLE AS $$
206
+ DECLARE
207
+ t mod.transforms;
208
+ out_value text;
209
+ BEGIN
210
+ SELECT * INTO t FROM mod.transforms x WHERE x.name = transform.name;
211
+ IF NOT FOUND THEN
212
+ RAISE EXCEPTION 'mod.transform: unknown transform %', name;
213
+ END IF;
214
+ EXECUTE format('SELECT (%s)::text FROM (SELECT ($1)::text AS value) AS v',
215
+ mod._compile_transform(t.expression, jsonb_build_object('v', 'mod.transform_input'::regclass::oid),
216
+ 'v.value', 'apply'))
217
+ INTO out_value USING value;
218
+ RETURN out_value;
219
+ END $$;
220
+
221
+ -- ----------------------------------------------------------------------------
222
+ -- Proposal kind transform
223
+ -- ----------------------------------------------------------------------------
224
+ ALTER TABLE mod.proposals DROP CONSTRAINT proposals_kind_check;
225
+ ALTER TABLE mod.proposals ADD CONSTRAINT proposals_kind_check
226
+ CHECK (kind IN ('comment', 'crosswalk', 'mapping', 'sensitivity', 'relationship', 'quality_rule', 'task', 'transform'));
227
+
228
+ ALTER FUNCTION mod._validate_proposal(text, jsonb, text[]) RENAME TO _validate_proposal_v9;
229
+ CREATE FUNCTION mod._validate_proposal(kind text, payload jsonb, scope text[]) RETURNS jsonb
230
+ LANGUAGE plpgsql AS $$
231
+ DECLARE
232
+ col text;
233
+ parts text[];
234
+ chk jsonb;
235
+ BEGIN
236
+ IF kind <> 'transform' THEN
237
+ RETURN mod._validate_proposal_v9(kind, payload, scope);
238
+ END IF;
239
+ IF coalesce(payload ->> 'name', '') !~ '^[a-z][a-z0-9_]*$' THEN
240
+ RAISE EXCEPTION 'transform: name must be lower-case letters, digits and underscores';
241
+ END IF;
242
+ IF payload ->> 'column' IS NULL THEN
243
+ RAISE EXCEPTION 'transform: column (schema.table.column) is required: the preview runs on its values';
244
+ END IF;
245
+ col := mod._column_name(payload ->> 'column');
246
+ parts := parse_ident(col);
247
+ IF scope IS NOT NULL AND NOT parts[1] = ANY (scope) THEN
248
+ RAISE EXCEPTION 'schema % is outside this run''s scope', parts[1];
249
+ END IF;
250
+ IF mod.policy_level(parts[1], parts[2], parts[3]) = 'deny' THEN
251
+ RAISE EXCEPTION 'no such object';
252
+ END IF;
253
+ PERFORM mod._compile_transform(payload -> 'expression', jsonb_build_object('t', to_regclass(format('%I.%I', parts[1], parts[2]))::oid),
254
+ 't.' || parts[3], 'check');
255
+ IF payload ->> 'output_type' IS NOT NULL AND to_regtype(payload ->> 'output_type') IS NULL THEN
256
+ RAISE EXCEPTION 'transform: unknown output_type %', payload ->> 'output_type';
257
+ END IF;
258
+ RETURN jsonb_build_object('target', 'transform:' || (payload ->> 'name'), 'payload', jsonb_strip_nulls(jsonb_build_object(
259
+ 'name', payload ->> 'name', 'description', payload ->> 'description', 'expression', payload -> 'expression',
260
+ 'column', col, 'output_type', payload ->> 'output_type',
261
+ 'before_version', (SELECT t.version FROM mod.transforms t WHERE t.name = payload ->> 'name'))));
262
+ END $$;
263
+
264
+ ALTER FUNCTION mod._preview_other(bigint) RENAME TO _preview_other_v9;
265
+ CREATE FUNCTION mod._preview_other(proposal_id bigint) RETURNS jsonb
266
+ LANGUAGE plpgsql AS $$
267
+ DECLARE
268
+ p mod.proposals;
269
+ BEGIN
270
+ SELECT * INTO p FROM mod.proposals WHERE id = proposal_id;
271
+ IF p.kind <> 'transform' THEN
272
+ RETURN mod._preview_other_v9(proposal_id);
273
+ END IF;
274
+ RETURN jsonb_build_object('id', p.id, 'kind', p.kind, 'target', p.target, 'status', p.status, 'after', p.payload,
275
+ 'rationale', p.rationale, 'evidence', p.evidence,
276
+ 'before', (SELECT to_jsonb(t) FROM mod.transforms t WHERE t.name = p.payload ->> 'name'),
277
+ 'stale', (SELECT t.version FROM mod.transforms t WHERE t.name = p.payload ->> 'name')
278
+ IS DISTINCT FROM (p.payload ->> 'before_version')::int,
279
+ 'check', mod.check_transform(p.payload -> 'expression', p.payload ->> 'column',
280
+ p.payload ->> 'output_type'));
281
+ END $$;
282
+
283
+ ALTER FUNCTION mod._apply_other(bigint, boolean) RENAME TO _apply_other_v9;
284
+ CREATE FUNCTION mod._apply_other(proposal_id bigint, force boolean) RETURNS text
285
+ LANGUAGE plpgsql AS $$
286
+ DECLARE
287
+ p mod.proposals;
288
+ reason text;
289
+ BEGIN
290
+ SELECT * INTO p FROM mod.proposals WHERE id = proposal_id FOR UPDATE;
291
+ IF p.kind <> 'transform' THEN
292
+ RETURN mod._apply_other_v9(proposal_id, force);
293
+ END IF;
294
+ IF p.status NOT IN ('approved', 'failed') THEN
295
+ RAISE EXCEPTION 'proposal % is %; approve it first', proposal_id, p.status;
296
+ END IF;
297
+ IF NOT force AND (SELECT t.version FROM mod.transforms t WHERE t.name = p.payload ->> 'name')
298
+ IS DISTINCT FROM (p.payload ->> 'before_version')::int THEN
299
+ reason := 'stale: the transform changed after the proposal; check mod.preview and apply with force => true';
300
+ ELSE
301
+ INSERT INTO mod.transforms AS t (name, description, expression, output_type, sample_column, proposal_id)
302
+ VALUES (p.payload ->> 'name', p.payload ->> 'description', p.payload -> 'expression', p.payload ->> 'output_type',
303
+ p.payload ->> 'column', p.id)
304
+ ON CONFLICT (name) DO UPDATE
305
+ SET description = EXCLUDED.description, expression = EXCLUDED.expression, output_type = EXCLUDED.output_type,
306
+ sample_column = EXCLUDED.sample_column, proposal_id = EXCLUDED.proposal_id, version = t.version + 1,
307
+ updated_at = now(), updated_by = session_user;
308
+ END IF;
309
+ IF reason IS NOT NULL THEN
310
+ UPDATE mod.proposals SET status = 'failed', error = reason WHERE id = proposal_id;
311
+ PERFORM mod._proposal_event(proposal_id, 'failed', reason);
312
+ RETURN 'failed';
313
+ END IF;
314
+ UPDATE mod.proposals SET status = 'applied', applied_at = now(), error = NULL WHERE id = proposal_id;
315
+ PERFORM mod._proposal_event(proposal_id, 'applied', format('transform %s', p.payload ->> 'name'));
316
+ RETURN 'applied';
317
+ END $$;
318
+
319
+ -- ----------------------------------------------------------------------------
320
+ -- Mapping compiler v2: transforms, delete propagation, incremental reads
321
+ -- ----------------------------------------------------------------------------
322
+ ALTER FUNCTION mod._compile_mapping(jsonb, text) RENAME TO _compile_mapping_v1;
323
+
324
+ CREATE FUNCTION mod._compile_mapping(spec jsonb, mode text DEFAULT 'apply', watermark_from text DEFAULT NULL,
325
+ watermark_to text DEFAULT NULL) RETURNS jsonb
326
+ LANGUAGE plpgsql STABLE AS $$
327
+ DECLARE
328
+ expanded jsonb;
329
+ c jsonb;
330
+ rels jsonb := '{}';
331
+ src jsonb;
332
+ inc_sql text;
333
+ bounds jsonb := '[]';
334
+ scope_sql text := '';
335
+ k text;
336
+ v jsonb;
337
+ target regclass;
338
+ BEGIN
339
+ IF jsonb_typeof(spec) IS DISTINCT FROM 'object' THEN
340
+ RAISE EXCEPTION 'mapping: the spec must be a JSON object';
341
+ END IF;
342
+ expanded := mod._expand_transforms(spec);
343
+ IF spec ? 'incremental' THEN
344
+ IF jsonb_typeof(spec -> 'incremental') <> 'object' OR NOT spec -> 'incremental' ? 'expr' THEN
345
+ RAISE EXCEPTION 'mapping: incremental must be {"expr": <a column or expression that only grows, e.g. "c.updated_at">}';
346
+ END IF;
347
+ IF coalesce((spec ->> 'delete_missing')::boolean, false) THEN
348
+ RAISE EXCEPTION 'mapping: delete_missing needs every source row, so it cannot be combined with incremental';
349
+ END IF;
350
+ IF watermark_from IS NOT NULL THEN
351
+ bounds := bounds || jsonb_build_object('op', '>', 'args', jsonb_build_array(expanded #> '{incremental,expr}',
352
+ jsonb_build_object('value', watermark_from)));
353
+ END IF;
354
+ IF watermark_to IS NOT NULL THEN
355
+ bounds := bounds || jsonb_build_object('op', '<=', 'args', jsonb_build_array(expanded #> '{incremental,expr}',
356
+ jsonb_build_object('value', watermark_to)));
357
+ END IF;
358
+ IF jsonb_array_length(bounds) > 0 THEN
359
+ IF expanded ? 'filter' AND expanded -> 'filter' <> 'null' THEN
360
+ bounds := bounds || jsonb_build_array(expanded -> 'filter');
361
+ END IF;
362
+ expanded := jsonb_set(expanded, '{filter}', CASE WHEN jsonb_array_length(bounds) = 1 THEN bounds -> 0
363
+ ELSE jsonb_build_object('op', 'and', 'args', bounds) END);
364
+ END IF;
365
+ END IF;
366
+
367
+ c := mod._compile_mapping_v1(expanded, mode);
368
+
369
+ FOR src IN SELECT * FROM jsonb_array_elements(spec -> 'sources') LOOP
370
+ rels := rels || jsonb_build_object(src ->> 'alias', to_regclass(src ->> 'relation')::oid);
371
+ END LOOP;
372
+ IF spec ? 'incremental' THEN
373
+ inc_sql := mod._compile_expr(expanded #> '{incremental,expr}', rels, mode);
374
+ c := c || jsonb_build_object('incremental', true,
375
+ 'watermark_sql', format('SELECT max(%s)::text FROM %s%s', inc_sql, c ->> 'from_sql',
376
+ -- the spec's own filter, without the watermark bounds
377
+ (mod._compile_mapping_v1(mod._expand_transforms(spec), mode)) ->> 'where_sql'));
378
+ END IF;
379
+
380
+ IF coalesce((spec ->> 'delete_missing')::boolean, false) THEN
381
+ IF c ->> 'mode' <> 'load' THEN
382
+ RAISE EXCEPTION 'mapping: delete_missing applies to mode load';
383
+ END IF;
384
+ target := (c ->> 'target_oid')::oid::regclass;
385
+ IF spec ? 'delete_scope' THEN
386
+ IF jsonb_typeof(spec -> 'delete_scope') <> 'object' THEN
387
+ RAISE EXCEPTION 'mapping: delete_scope must be {"target_column": literal, ...}';
388
+ END IF;
389
+ FOR k, v IN SELECT * FROM jsonb_each(spec -> 'delete_scope') LOOP
390
+ IF NOT EXISTS (SELECT FROM pg_attribute a WHERE a.attrelid = target AND a.attname = k AND a.attnum > 0
391
+ AND NOT a.attisdropped) THEN
392
+ RAISE EXCEPTION 'mapping: delete_scope: % has no column %', target, k;
393
+ END IF;
394
+ scope_sql := scope_sql || format(' AND t.%I = %s', k, mod._compile_literal(v));
395
+ END LOOP;
396
+ END IF;
397
+ c := c || jsonb_build_object('delete_sql', format(
398
+ 'DELETE FROM %s AS t WHERE true%s AND NOT EXISTS (SELECT FROM (%s) s WHERE %s)',
399
+ target, scope_sql, c ->> 'select',
400
+ (SELECT string_agg(format('t.%I = s.%I', x, x), ' AND ') FROM jsonb_array_elements_text(c -> 'key') x)));
401
+ END IF;
402
+ RETURN c;
403
+ END $$;
404
+
405
+ ALTER TABLE mod.mappings
406
+ ADD COLUMN watermark text,
407
+ ADD COLUMN last_run_deleted bigint;
408
+ COMMENT ON COLUMN mod.mappings.watermark IS 'Highest value of incremental.expr loaded so far; the next run reads rows above it';
409
+
410
+ CREATE OR REPLACE FUNCTION mod.run_mapping(name text, force boolean DEFAULT false) RETURNS bigint
411
+ LANGUAGE plpgsql AS $$
412
+ DECLARE
413
+ m mod.mappings;
414
+ c jsonb;
415
+ n bigint;
416
+ d bigint;
417
+ high text;
418
+ BEGIN
419
+ SELECT * INTO m FROM mod.mappings WHERE mappings.name = run_mapping.name FOR UPDATE;
420
+ IF NOT FOUND THEN
421
+ RAISE EXCEPTION 'mod.run_mapping: no mapping %', run_mapping.name;
422
+ END IF;
423
+ BEGIN
424
+ c := mod._compile_mapping(m.spec, 'apply');
425
+ IF c ? 'watermark_sql' THEN
426
+ EXECUTE c ->> 'watermark_sql' INTO high;
427
+ c := mod._compile_mapping(m.spec, 'apply', m.watermark, high);
428
+ END IF;
429
+ EXCEPTION WHEN OTHERS THEN
430
+ UPDATE mod.mappings SET last_run_error = 'drift: ' || SQLERRM WHERE mappings.name = m.name;
431
+ RAISE EXCEPTION 'mod.run_mapping: % no longer compiles (drift): %', m.name, SQLERRM;
432
+ END;
433
+ IF c ->> 'fingerprint' <> m.fingerprint AND NOT force THEN
434
+ RAISE EXCEPTION 'mod.run_mapping: a source or the target of % changed shape since it was applied (drift)', m.name
435
+ USING HINT = 'Check it with mod.check_mapping((SELECT spec FROM mod.mappings WHERE name = ...)), then run with force => true.';
436
+ END IF;
437
+ n := 0;
438
+ IF NOT (c ? 'watermark_sql') OR high IS NOT NULL THEN
439
+ EXECUTE c ->> 'apply';
440
+ GET DIAGNOSTICS n = ROW_COUNT;
441
+ END IF;
442
+ IF c ? 'delete_sql' THEN
443
+ EXECUTE c ->> 'delete_sql';
444
+ GET DIAGNOSTICS d = ROW_COUNT;
445
+ END IF;
446
+ UPDATE mod.mappings
447
+ SET last_run_at = now(), last_run_rows = n, last_run_deleted = d, last_run_error = NULL,
448
+ watermark = coalesce(high, watermark),
449
+ fingerprint = CASE WHEN force THEN c ->> 'fingerprint' ELSE fingerprint END
450
+ WHERE mappings.name = m.name;
451
+ RETURN n + coalesce(d, 0);
452
+ END $$;
453
+
454
+ -- Resets an incremental mapping so its next run reads every source row again.
455
+ CREATE FUNCTION mod.reset_watermark(name text) RETURNS void
456
+ LANGUAGE sql AS $$
457
+ UPDATE mod.mappings SET watermark = NULL WHERE mappings.name = reset_watermark.name;
458
+ $$;
459
+
460
+ -- check_mapping also reports what a delete would remove.
461
+ ALTER FUNCTION mod.check_mapping(jsonb, boolean) RENAME TO _check_mapping_v1;
462
+ CREATE FUNCTION mod.check_mapping(spec jsonb, try_insert boolean DEFAULT true) RETURNS jsonb
463
+ LANGUAGE plpgsql AS $$
464
+ DECLARE
465
+ res jsonb := mod._check_mapping_v1(mod._expand_transforms_safe(spec), try_insert);
466
+ c jsonb;
467
+ n bigint;
468
+ BEGIN
469
+ BEGIN
470
+ c := mod._compile_mapping(spec, 'check');
471
+ EXCEPTION WHEN OTHERS THEN
472
+ RETURN res || CASE WHEN res ->> 'ok' = 'true'
473
+ THEN jsonb_build_object('ok', false, 'issues', (res -> 'issues')
474
+ || jsonb_build_array(mod._issue('error', 'compile', SQLERRM)))
475
+ ELSE '{}'::jsonb END;
476
+ END;
477
+ IF c ? 'delete_sql' THEN
478
+ BEGIN
479
+ EXECUTE format('SELECT count(*) FROM %s AS t WHERE %s', c ->> 'target',
480
+ substr(c ->> 'delete_sql', position(' WHERE ' IN c ->> 'delete_sql') + 7))
481
+ INTO n;
482
+ res := jsonb_set(res, '{counts,would_delete}', to_jsonb(n));
483
+ IF n > 0 THEN
484
+ res := jsonb_set(res, '{issues}', (res -> 'issues') || jsonb_build_array(
485
+ mod._issue('info', 'delete', format('%s target rows no longer produced by the mapping would be deleted', n))));
486
+ END IF;
487
+ EXCEPTION WHEN OTHERS THEN
488
+ NULL;
489
+ END;
490
+ END IF;
491
+ RETURN res;
492
+ END $$;
493
+
494
+ CREATE FUNCTION mod._expand_transforms_safe(spec jsonb) RETURNS jsonb
495
+ LANGUAGE plpgsql STABLE AS $$
496
+ BEGIN
497
+ RETURN mod._expand_transforms(spec);
498
+ EXCEPTION WHEN OTHERS THEN
499
+ RETURN spec; -- the compile step reports the problem
500
+ END $$;
501
+
502
+ -- ----------------------------------------------------------------------------
503
+ -- Privileges
504
+ -- ----------------------------------------------------------------------------
505
+ REVOKE ALL ON ALL ROUTINES IN SCHEMA mod FROM PUBLIC;
506
+ GRANT EXECUTE ON FUNCTION mod._capture(), mod._enqueue(bigint, jsonb, jsonb), mod._fp(text),
507
+ mod.normalize_value(text), mod._capture_truncate(), mod._enqueue_truncate(bigint),
508
+ mod._check_capture(), mod._check_enqueue(text, jsonb), mod._value_key(text),
509
+ mod._context_hash(jsonb) TO PUBLIC;
510
+
511
+ GRANT SELECT ON mod.code_embeddings, mod.transforms TO modelcall_user;
512
+ GRANT USAGE ON TYPE mod.transform_input TO modelcall_user, modelcall_agent, modelcall_engine;
513
+ GRANT EXECUTE ON FUNCTION mod.check_transform(jsonb, text, text, int), mod.transform(text, text),
514
+ mod._compile_transform(jsonb, jsonb, text, text), mod._substitute(jsonb, text, jsonb),
515
+ mod._expand_transforms(jsonb, int), mod._expand_transforms_safe(jsonb),
516
+ mod._compile_mapping(jsonb, text, text, text), mod._compile_mapping_v1(jsonb, text),
517
+ mod.check_mapping(jsonb, boolean), mod._check_mapping_v1(jsonb, boolean),
518
+ mod._validate_proposal(text, jsonb, text[]), mod._validate_proposal_v9(text, jsonb, text[]),
519
+ mod._preview_other(bigint), mod._preview_other_v9(bigint), mod._column_name(text),
520
+ mod._input_is_valid(text, text), mod._input_check_fn()
521
+ TO modelcall_user, modelcall_agent;
522
+ GRANT SELECT ON mod.transforms TO modelcall_agent;
523
+
524
+ GRANT EXECUTE ON FUNCTION mod.create_domain(text, regclass, text, text, text[], text, text, boolean, text, int)
525
+ TO modelcall_admin;
526
+
527
+ GRANT INSERT, UPDATE ON mod.transforms TO modelcall_reviewer;
528
+ GRANT UPDATE ON mod.mappings TO modelcall_reviewer;
529
+ GRANT EXECUTE ON FUNCTION mod._apply_other(bigint, boolean), mod._apply_other_v9(bigint, boolean),
530
+ mod.run_mapping(text, boolean), mod.reset_watermark(text)
531
+ TO modelcall_reviewer;
532
+
533
+ GRANT SELECT, INSERT, UPDATE, DELETE ON mod.code_embeddings TO modelcall_engine;
534
+ GRANT EXECUTE ON FUNCTION mod._validate_proposal(text, jsonb, text[]), mod._validate_proposal_v9(text, jsonb, text[]),
535
+ mod._compile_transform(jsonb, jsonb, text, text), mod._substitute(jsonb, text, jsonb),
536
+ mod._expand_transforms(jsonb, int), mod._compile_mapping(jsonb, text, text, text),
537
+ mod._compile_mapping_v1(jsonb, text), mod._column_name(text)
538
+ TO modelcall_engine;
539
+
540
+ INSERT INTO mod.migrations (id) VALUES ('0011_standardization');