causilo-db 0.2.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.
@@ -0,0 +1,605 @@
1
+ Metadata-Version: 2.4
2
+ Name: causilo-db
3
+ Version: 0.2.0
4
+ Summary: Predict the blank cells of a database column with the hosted Causilo API.
5
+ Author-email: "Nums AI Inc." <api@nums.world>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://nums.world
8
+ Project-URL: Documentation, https://docs.nums.world
9
+ Project-URL: Source, https://github.com/nums-ai/causilo-db
10
+ Project-URL: Issues, https://github.com/nums-ai/causilo-db/issues
11
+ Project-URL: Changelog, https://github.com/nums-ai/causilo-db/blob/main/CHANGELOG.md
12
+ Keywords: causilo,tabular,prediction,sql,database,postgresql,duckdb,snowflake,spark,databricks
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Database
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.11
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: causilo-client>=1.0.6
27
+ Requires-Dist: pandas>=2.0
28
+ Requires-Dist: numpy>=1.24
29
+ Requires-Dist: pyarrow>=14
30
+ Requires-Dist: sqlalchemy>=2.0
31
+ Provides-Extra: duckdb
32
+ Requires-Dist: duckdb>=1.0; extra == "duckdb"
33
+ Provides-Extra: postgres
34
+ Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
35
+ Provides-Extra: mysql
36
+ Requires-Dist: pymysql>=1.1; extra == "mysql"
37
+ Provides-Extra: spark
38
+ Requires-Dist: pyspark>=3.5; extra == "spark"
39
+ Provides-Extra: mssql
40
+ Requires-Dist: pymssql>=2.3; extra == "mssql"
41
+ Provides-Extra: oracle
42
+ Requires-Dist: oracledb>=2.0; extra == "oracle"
43
+ Provides-Extra: clickhouse
44
+ Requires-Dist: clickhouse-sqlalchemy>=0.3; extra == "clickhouse"
45
+ Provides-Extra: trino
46
+ Requires-Dist: trino[sqlalchemy]>=0.330; extra == "trino"
47
+ Provides-Extra: snowflake
48
+ Requires-Dist: snowflake-sqlalchemy>=1.6; extra == "snowflake"
49
+ Provides-Extra: redshift
50
+ Requires-Dist: sqlalchemy-redshift>=0.8; extra == "redshift"
51
+ Requires-Dist: redshift_connector>=2.1; extra == "redshift"
52
+ Provides-Extra: bigquery
53
+ Requires-Dist: sqlalchemy-bigquery>=1.11; extra == "bigquery"
54
+ Provides-Extra: dev
55
+ Requires-Dist: pytest>=8; extra == "dev"
56
+ Requires-Dist: duckdb>=1.0; extra == "dev"
57
+ Requires-Dist: psycopg[binary]>=3.1; extra == "dev"
58
+ Requires-Dist: pymysql>=1.1; extra == "dev"
59
+ Requires-Dist: pyyaml>=6; extra == "dev"
60
+ Dynamic: license-file
61
+
62
+ # causilo-db
63
+
64
+ causilo-db predicts the blank cells of a database column. Rows where the
65
+ column has a value are the examples, rows where it is blank are predicted, and
66
+ the predictions come back as a table. The source table is never modified.
67
+
68
+ The predictions are made by Causilo, the hosted tabular prediction API from
69
+ Nums AI (`https://api.nums.world`, documentation at
70
+ [docs.nums.world](https://docs.nums.world)). You need your own Causilo API key,
71
+ and every call counts against that key's account.
72
+
73
+ What leaves your database: the target and feature columns of the blank rows
74
+ and of up to 50,000 filled rows, sent over HTTPS. The id column is not sent.
75
+ `features` and `where` narrow what is read. causilo-db stores neither the data
76
+ nor the key.
77
+
78
+ Requires Python 3.11 or later. The code is under the Apache License 2.0; the
79
+ two example tables keep their own licences (CC BY 4.0 and CC0).
80
+
81
+ | Use it from | Call |
82
+ |---|---|
83
+ | Any database SQLAlchemy reaches | `causilo-db predict <url> <table> <column>` or `causilo_db.predict_table(...)` |
84
+ | PostgreSQL, inside the database (PL/Python, or the `http` extension) | `SELECT * FROM causilo.predict('customers', 'churn', 'customer_id')` |
85
+ | DuckDB | `causilo_db.duckdb.predict(con, 'customers', 'churn')`, returns a relation |
86
+ | Spark, Databricks | `causilo_db.spark.predict_table(spark, 'main.sales.customers', 'churn', ...)` |
87
+ | Snowflake, inside the warehouse | `CALL CAUSILO.PREDICT('SALES.CUSTOMERS', 'CHURN', 'CUSTOMER_ID')` |
88
+ | Snowflake, as a Native App | `CALL CAUSILO.CORE.PREDICT('SALES.PUBLIC.CUSTOMERS', 'CHURN', 'CUSTOMER_ID')` |
89
+ | BigQuery, inside the warehouse | `SELECT ds.causilo_predict('p.ds.customers', 'churn', 'customer_id', 'p.ds.churn_pred')` |
90
+
91
+ The SQL installers, the Snowflake Native App, the BigQuery service, the
92
+ Databricks notebook and the scripts are not installed by `pip install`; they are in the [GitHub repository](https://github.com/nums-ai/causilo-db)
93
+ and in the source archive on PyPI. Clone the repository, or download the one
94
+ file you need. What has been run against the live API is under [Tested](#tested).
95
+
96
+ ## The result
97
+
98
+ One row per blank cell, with the id column you name (or `row_number`, the
99
+ 0-based position in what was read; `ctid` in the PostgreSQL function):
100
+
101
+ - a number column (regression): the target column holds the predicted value
102
+ (the median), and `<column>_p25`, `<column>_p50`, `<column>_p75` hold the
103
+ predicted quartiles; the true value should fall between p25 and p75 about
104
+ half the time;
105
+ - anything else (classification): the most likely class,
106
+ `<column>_probability` for it, and `<column>_prob_<class>` for every class
107
+ (characters other than letters, digits and `_` in the class become `_`, names
108
+ are cut to 56 characters, and names that would clash get a number, so every
109
+ database takes them).
110
+
111
+ The PostgreSQL function returns fixed columns instead: `row_id`, `prediction`
112
+ (as text), `probability`, `p25`, `p50`, `p75`. Snowflake returns the names
113
+ above in upper case.
114
+
115
+ A numeric column with 20 or fewer distinct whole values is read as classes;
116
+ pass `task='reg'` or `--task reg` to say otherwise (the Snowflake procedure has
117
+ no such argument). A text column with more than 200 distinct values is refused
118
+ unless you pass `task='clf'`, since it is more likely a name than a class.
119
+ DECIMAL columns are read as numbers, and dates and timestamps are sent as
120
+ seconds since 1970.
121
+
122
+ Every column except the target and the id is a feature unless you pass
123
+ `features`. The PostgreSQL function and the Snowflake procedure take no
124
+ `features` or `where`; point them at a view to choose columns or rows. The
125
+ filled rows are sampled down to at most 50,000, fewer for a wide table so that
126
+ each call stays under 7,000,000 cells, and a large table is sent in several
127
+ calls.
128
+
129
+ Each of those calls is charged when it completes. If a later call fails, the
130
+ predictions of the calls before it are not returned, and the error says how
131
+ many calls had completed and been charged (in Python,
132
+ `causilo_db.PartialPredictionError`, with `calls_completed`, raised from the
133
+ original error); running again pays for them again. A call that was answered
134
+ but whose answer cannot be used counts among the charged calls, even when it
135
+ is the first. A first call that fails before the API answers is the original
136
+ error.
137
+
138
+ ## API key
139
+
140
+ causilo-db never writes the key into a table or a file:
141
+
142
+ - command line and Python: `CAUSILO_API_KEY` in the environment, or `api_key=`;
143
+ - PostgreSQL function: `SET causilo.api_key = 'csl_...';` for the session. The
144
+ statement is ordinary SQL, so it shows in `pg_stat_activity` and, with
145
+ `log_statement` on, in the server log. With the PL/Python function,
146
+ `CAUSILO_API_KEY` in the server's environment works too, and every role that
147
+ can call the function then spends that key;
148
+ - Snowflake: a Snowflake secret you set once;
149
+ - Databricks: a secret scope, `dbutils.secrets.get("causilo", "api_key")`.
150
+
151
+ ## Python
152
+
153
+ ```python
154
+ from causilo_db import predict_table
155
+
156
+ result, pred = predict_table("postgresql+psycopg://user@host/shop", "customers", "churn",
157
+ id_column="customer_id", out_table="customers_churn_prediction")
158
+ print(pred.task, pred.n_query, pred.n_context, pred.notes)
159
+ ```
160
+
161
+ `result` is a pandas DataFrame and `pred` describes what was sent.
162
+ `causilo_db.predict_frame(df, "churn")` does the same for a DataFrame you
163
+ already have.
164
+
165
+ ## Command line
166
+
167
+ ```bash
168
+ pip install "causilo-db[postgres]" # or [mysql], [mssql], [oracle], [clickhouse], [trino], [redshift], [bigquery], [snowflake]
169
+ export CAUSILO_API_KEY=csl_...
170
+ causilo-db predict postgresql+psycopg://user@host/shop customers churn \
171
+ --id customer_id --out customers_churn_prediction
172
+ ```
173
+
174
+ The URL names the driver that the extra installs:
175
+
176
+ | Extra | URL |
177
+ |---|---|
178
+ | `postgres` | `postgresql+psycopg://user:password@host/db` |
179
+ | `mysql` | `mysql+pymysql://user:password@host/db` |
180
+ | `mssql` | `mssql+pymssql://user:password@host/db` |
181
+ | `oracle` | `oracle+oracledb://user:password@host/?service_name=FREEPDB1` |
182
+ | `clickhouse` | `clickhouse+native://user:password@host/db` |
183
+ | `trino` | `trino://user@host:8080/catalog/schema` |
184
+ | `redshift` | `redshift+redshift_connector://user:password@host:5439/db` |
185
+ | `bigquery` | `bigquery://project/dataset` |
186
+ | `snowflake` | `snowflake://user:password@account/db/schema?warehouse=wh` |
187
+
188
+ A password in the URL shows in shell history and the process list; where the
189
+ driver has its own password file or environment variables (`~/.pgpass`,
190
+ `PGPASSWORD`, `~/.my.cnf`), prefer those.
191
+
192
+ Without `--out` the result is printed as CSV. `--where "region = 'KR'"` reads
193
+ part of a table, `--features a,b,c` picks the features, `--schema` names the
194
+ schema, `--out-schema` the schema of the result, `--if-exists replace`
195
+ overwrites an earlier result and `--if-exists append` adds to it. If the
196
+ prediction succeeds but the table cannot be written, the result is printed as
197
+ CSV instead, so nothing that was paid for is lost.
198
+
199
+ The result table is written with types each database accepts: Oracle gets
200
+ `BINARY_DOUBLE` and `VARCHAR2`, ClickHouse a `MergeTree` table, on Trino
201
+ names such as `trim` are quoted, and on Redshift and BigQuery rows go in batches
202
+ of one multi-row INSERT rather than one statement each.
203
+
204
+ ## PostgreSQL function
205
+
206
+ On a server where you can install PL/Python (`plpython3u`) and the
207
+ `causilo-db` package into the Python the server runs:
208
+
209
+ ```sql
210
+ \i sql/postgres/install.sql -- from a clone of this repository, as a superuser
211
+ SET causilo.api_key = 'csl_...';
212
+ SELECT * FROM causilo.predict('concrete', 'strength', 'mix_id');
213
+ SELECT * FROM causilo.predict('orders', 'units', 'order_id', task => 'reg');
214
+ CREATE TABLE churn_scores AS SELECT * FROM causilo.predict('customers', 'churn', 'customer_id');
215
+ ```
216
+
217
+ The function reads the table as the role that calls it. A view works when an id
218
+ column is given; without one, `row_id` is the row's `ctid`, which changes when
219
+ the row is updated. `docker/postgres.Dockerfile` builds a PostgreSQL 16 with
220
+ PL/Python and causilo-db, for trying it locally.
221
+
222
+ Most hosted PostgreSQL services do not allow `plpython3u`. Where the `http`
223
+ extension is allowed, use the function below instead; elsewhere, run the
224
+ command line from outside the database.
225
+
226
+ ## PostgreSQL function without Python
227
+
228
+ `sql/postgres/install_http.sql` creates the same `causilo.predict` in PL/pgSQL
229
+ on the [`http` extension](https://github.com/pramsey/pgsql-http) (pgsql-http
230
+ 1.6 or later, which can send a binary body). The function builds the request,
231
+ two Parquet tables, in SQL and calls the API itself, so nothing is installed
232
+ on the server's file system and no Python runs in the database.
233
+
234
+ ```sql
235
+ CREATE EXTENSION IF NOT EXISTS http WITH SCHEMA extensions; -- Supabase keeps extensions there
236
+ \i sql/postgres/install_http.sql
237
+ SET causilo.api_key = 'csl_...';
238
+ SELECT * FROM causilo.predict('concrete', 'strength', 'mix_id');
239
+ ```
240
+
241
+ The installer refuses an `http` older than 1.6; `ALTER EXTENSION http UPDATE`
242
+ first. Two optional settings: `causilo.endpoint` (default
243
+ `https://api.nums.world`) and `causilo.timeout_ms`, how long one call may take
244
+ (default 900000, fifteen minutes, as in the Python client). Hosted services
245
+ often set a `statement_timeout` for each role; a large prediction can need
246
+ `SET statement_timeout = '20min'` for the session. When `statement_timeout`
247
+ or a cancel from the client stops the function during a call, the function
248
+ asks the API to cancel that call, waiting at most five seconds for the answer;
249
+ a call the API had already started is charged all the same. Calls that had
250
+ completed before it were charged too, and the error says how many. The database server must be
251
+ able to reach `api.nums.world` on port 443.
252
+
253
+ Where it can be used, from each provider's extension list in November 2026:
254
+
255
+ | Service | `http` extension | `plpython3u` | Use |
256
+ |---|---|---|---|
257
+ | [Supabase](https://supabase.com/docs/guides/database/extensions/http) | yes, 1.6.1 on PostgreSQL 15 and 17 ([build pins](https://github.com/supabase/postgres/blob/develop/nix/ext/versions.json); the PostgreSQL 15 build also carries 1.5.0, too old) | not listed | `install_http.sql` |
258
+ | [Crunchy Bridge](https://docs.crunchybridge.com/extensions-and-languages) | yes | [yes](https://docs.crunchybridge.com/extensions-and-languages/python), but `install.sql` also needs the causilo-db package in the server's Python | `install_http.sql` |
259
+ | [Amazon RDS for PostgreSQL](https://docs.aws.amazon.com/AmazonRDS/latest/PostgreSQLReleaseNotes/postgresql-extensions.html), [Aurora PostgreSQL](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraPostgreSQLReleaseNotes/AuroraPostgreSQL.Extensions.html) | no | no | command line |
260
+ | [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/extensions), [AlloyDB](https://cloud.google.com/alloydb/docs/reference/extensions) | no | no | command line |
261
+ | [Azure Database for PostgreSQL flexible server](https://learn.microsoft.com/en-us/azure/postgresql/extensions/concepts-extensions-versions) | no | no | command line |
262
+ | [Neon](https://neon.com/docs/extensions/pg-extensions), [Aiven](https://aiven.io/docs/products/postgresql/reference/list-of-extensions), [DigitalOcean](https://docs.digitalocean.com/products/databases/postgresql/details/supported-extensions/), [Render](https://render.com/docs/postgresql-extensions) | no | no | command line |
263
+
264
+ The cloud providers have their own routes out of SQL instead, each to their
265
+ own services rather than to any HTTPS address: `aws_lambda` on RDS and Aurora
266
+ (and `aws_ml` on Aurora) calls AWS Lambda, SageMaker and Bedrock;
267
+ `google_ml_integration` on Cloud SQL and AlloyDB registers model endpoints
268
+ that take and return JSON; `azure_ai` on Azure calls Azure OpenAI, Azure AI
269
+ services and one configured Azure Machine Learning endpoint. causilo-db has no
270
+ installer for these. Supabase's `pg_net` is asynchronous and sends only JSON,
271
+ so it cannot carry the request either.
272
+
273
+ What it does the same as `install.sql`: the arguments and the six result
274
+ columns, `row_id` from the id column or the `ctid`, the target's type deciding
275
+ regression or classification (20 distinct whole values, 200 text values), the
276
+ features and their types (an integer column with a blank goes as a float, a
277
+ boolean column with a blank as text, dates as seconds since 1970, blank
278
+ columns dropped), the class labels, the split into calls by cell count, and
279
+ every refusal before a call is made. On the two example tables it sent the
280
+ same tables and returned the same predictions as the PL/Python function, row
281
+ for row (see [Tested](#tested)).
282
+
283
+ Where it differs:
284
+
285
+ - the key comes only from `causilo.api_key`, not from `CAUSILO_API_KEY` in the
286
+ server's environment;
287
+ - above 50,000 filled rows (fewer for a wide table) the context is sampled by
288
+ a hash of each row's position rather than by NumPy's random draw, so a large
289
+ table gets a different sample, and slightly different predictions, than the
290
+ other adapters;
291
+ - the table is read more than once (counts first, then the rows sent). A
292
+ write in between that changes the counts stops the function with "the table
293
+ changed while it was being read"; to read one snapshot, run it inside
294
+ `BEGIN ISOLATION LEVEL REPEATABLE READ;` ... `COMMIT;`;
295
+ - the notes the other adapters return (columns dropped, dates converted,
296
+ context sampled) are raised as `NOTICE`s;
297
+ - array and composite values are sent in PostgreSQL's text form (`{1,2}`)
298
+ rather than Python's (`[1, 2]`), a date or timestamp target read as classes
299
+ keeps PostgreSQL's text form, and an id column of type `real`, `double
300
+ precision` or `boolean` comes back as PostgreSQL prints it (`1`, `true`
301
+ rather than `1.0`, `True`);
302
+ - a failure to connect is not retried, since the extension cannot tell
303
+ whether the request had left; a call that times out is cancelled, as the
304
+ Python client does, which refunds it if it had not started. HTTP failures
305
+ are retried as the client retries them (429, 500, 503, or what the server
306
+ marks retryable; never 502 or 504);
307
+ - the request is built in the database server's memory. A full call of
308
+ 7,000,000 numeric cells is about 60 MB of request; 20,000 rows of 301 features took
309
+ 18 seconds to build against a stand-in API, 200,000 rows of 11 features 4
310
+ seconds.
311
+
312
+ `docker/postgres-http.Dockerfile` builds a PostgreSQL 17 with pgsql-http
313
+ 1.6.1 and the function, for trying it locally.
314
+
315
+ ## DuckDB
316
+
317
+ ```python
318
+ # pip install "causilo-db[duckdb]"
319
+ import duckdb, causilo_db.duckdb as cx
320
+
321
+ con = duckdb.connect("shop.duckdb")
322
+ rel = cx.predict(con, "customers", "churn", id_column="customer_id")
323
+ rel.create("customers_churn_prediction")
324
+ ```
325
+
326
+ ## Spark and Databricks
327
+
328
+ ```python
329
+ # pip install "causilo-db[spark]" (Databricks already has Spark: pip install causilo-db)
330
+ from causilo_db.spark import predict, predict_table
331
+
332
+ out = predict(spark.table("main.sales.customers"), "churn", id_column="customer_id")
333
+ predict_table(spark, "main.sales.customers", "churn", id_column="customer_id",
334
+ output_table="main.sales.customers_churn_prediction",
335
+ api_key=dbutils.secrets.get("causilo", "api_key"))
336
+ ```
337
+
338
+ The table stays in Spark. Only the rows to predict and a sample of at most
339
+ 50,000 filled rows, drawn inside Spark, reach the driver. Past 1,000,000 rows to
340
+ predict it stops and asks you to filter first (`max_query_rows=` raises it).
341
+ Without `id_column` the result is the blank rows themselves with the target
342
+ filled in and the other prediction columns after; the rows pass through pandas,
343
+ so an integer column with blanks comes back as a double. `predict_table` refuses
344
+ an existing `output_table` before predicting unless you pass
345
+ `mode='overwrite'` or `mode='append'`.
346
+
347
+ `notebooks/databricks_predict.py` is the same as a Databricks notebook. It needs:
348
+
349
+ - Python 3.11 or later. It was run on Databricks Runtime 16.4 LTS; check the
350
+ Python version of other runtimes and serverless environments first;
351
+ - outbound HTTPS to `api.nums.world`. Classic compute has it. Serverless compute
352
+ on Free Edition and on trial workspaces reaches only a fixed list of hosts,
353
+ and opening another host takes a serverless network policy.
354
+
355
+ ## Snowflake procedure
356
+
357
+ `sql/snowflake/install.sql` creates a network rule for `api.nums.world`, a
358
+ secret for the key, an external access integration and the procedure, in a
359
+ `CAUSILO` schema of the current database (`USE DATABASE ...` first). Run the
360
+ file as a role that can create integrations (ACCOUNTADMIN or one granted it),
361
+ then put your key in the secret. Running the file again later keeps the key.
362
+
363
+ ```sql
364
+ ALTER SECRET CAUSILO.API_KEY SET SECRET_STRING = 'csl_...';
365
+ CALL CAUSILO.PREDICT('SALES.CUSTOMERS', 'CHURN', 'CUSTOMER_ID');
366
+ CREATE TABLE SALES.CHURN_PREDICTION AS SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
367
+ ```
368
+
369
+ The procedure carries `causilo_db/core.py` inline and takes `causilo-client`
370
+ from PyPI through Snowflake's shared artifact repository, so nothing is uploaded
371
+ to a stage. `scripts/build_snowflake_sql.py` regenerates the file after a change
372
+ to the core. Trial accounts refuse external access integrations, so the account
373
+ needs billing set up first.
374
+
375
+ The procedure runs with the caller's rights, so it reads only the tables the
376
+ calling role can read. Every role granted USAGE on it spends the key in the
377
+ secret.
378
+
379
+ ## Snowflake Native App
380
+
381
+ `snowflake/native_app/` packages the same procedure as a Snowflake Native App,
382
+ so that an account installs it as an application instead of running
383
+ `install.sql`. The app requests the account-level CREATE EXTERNAL ACCESS
384
+ INTEGRATION privilege, which lets it create external access integrations in
385
+ the consumer account; it uses it to create one, to `api.nums.world` only (its
386
+ network rule allows that host and nothing else), which works once an
387
+ administrator approves the app's `CAUSILO_API` specification; the key is a sensitive configuration value of the
388
+ app, redacted from query history. The app reads with its own rights, so it sees
389
+ only the tables granted to it:
390
+
391
+ ```sql
392
+ ALTER APPLICATION CAUSILO SET CONFIGURATION CAUSILO_API_KEY VALUE = 'csl_...';
393
+ GRANT USAGE ON DATABASE SALES TO APPLICATION CAUSILO;
394
+ GRANT USAGE ON SCHEMA SALES.PUBLIC TO APPLICATION CAUSILO;
395
+ GRANT SELECT ON TABLE SALES.PUBLIC.CUSTOMERS TO APPLICATION CAUSILO;
396
+ CALL CAUSILO.CORE.PREDICT('SALES.PUBLIC.CUSTOMERS', 'CHURN', 'CUSTOMER_ID');
397
+ ```
398
+
399
+ The procedure takes the same arguments and returns the same columns as
400
+ `CAUSILO.PREDICT`; name the table in full. Every role granted the app's
401
+ `APP_USER` or `APP_ADMIN` role can predict from every table granted to the app
402
+ and spends the key. [`snowflake/native_app/README.md`](https://github.com/nums-ai/causilo-db/blob/main/snowflake/native_app/README.md)
403
+ is the consumer guide shown in Snowsight.
404
+
405
+ `scripts/build_snowflake_app.py` writes `manifest.yml` and `setup.sql`, with
406
+ `causilo_db/core.py` inlined. `causilo-client` is bundled as a zip on the
407
+ app's stage rather than taken from PyPI. `scripts/deploy_snowflake_app.py`
408
+ creates a test application package in your account, registers a version on its
409
+ QA release channel, installs the app from it, approves the specification, sets
410
+ the key and runs the two example tables through it, scored as under
411
+ [Tested](#tested); `--cleanup` drops what it created. It needs
412
+ `pip install snowflake-connector-python`, a role that can create application
413
+ packages, applications and databases (ACCOUNTADMIN by default), and
414
+ `SNOWFLAKE_ACCOUNT`, `SNOWFLAKE_USER`, `SNOWFLAKE_PASSWORD` (a programmatic
415
+ access token) and `CAUSILO_API_KEY_FILE` in the environment. The app was run
416
+ this way against the live API (see [Tested](#tested)); it is not yet listed on
417
+ the Snowflake Marketplace.
418
+
419
+ ## BigQuery remote function
420
+
421
+ `bigquery/` holds a small Cloud Run service that you deploy in your own GCP
422
+ project, and a BigQuery
423
+ [remote function](https://cloud.google.com/bigquery/docs/remote-functions) in
424
+ front of it. A prediction needs the whole table, while a remote function is
425
+ called row by row, so the function takes table names rather than values: the
426
+ service reads the source table with the BigQuery API, predicts, writes the
427
+ result to a new table and returns one line saying what it did.
428
+
429
+ ```sql
430
+ SELECT analytics.causilo_predict(
431
+ 'my-project.analytics.customers', 'churn', 'customer_id',
432
+ 'my-project.analytics.customers_churn_prediction');
433
+ -- predicted 1,204 blank cells of churn (classification) from 48,796 rows in 1 call; wrote ...
434
+
435
+ SELECT analytics.causilo_predict_with_options(
436
+ 'my-project.analytics.orders', 'units', 'order_id', 'my-project.analytics.orders_units',
437
+ '{"features": "price,region,week", "task": "reg"}');
438
+ ```
439
+
440
+ The result table has the id column and the columns described under
441
+ [The result](#the-result). The id column is required, and a NULL is refused: a
442
+ table read through the API has no fixed row order, so a `row_number` could not
443
+ be joined back. `options` takes `features` (a list, or names separated by
444
+ commas) and `task`; for anything else, point the function at a view.
445
+
446
+ The id and target names must hold only letters, digits and `_` and not start
447
+ with a digit, and `<target>_probability` must fit in 300 characters; a load
448
+ job takes other names only where flexible column names are enabled, so such a
449
+ call is refused before anything is paid for. Rename the columns in a view.
450
+
451
+ Deploy from a clone of this repository, logged in with gcloud as someone who
452
+ can enable APIs, create service accounts and grant roles:
453
+
454
+ ```bash
455
+ PROJECT=my-project REGION=us-central1 DATASET=analytics KEY_FILE=~/causilo.key \
456
+ bigquery/deploy.sh
457
+ ```
458
+
459
+ The script enables the APIs, builds the image with Cloud Build into an
460
+ Artifact Registry repository (the build runs as a service account of its own
461
+ that may only read its source bucket, push to the repository and write logs;
462
+ `BUILD=docker` builds the image locally instead), puts the key in a
463
+ Secret Manager secret, creates a service account for the service, deploys the
464
+ service with `--no-allow-unauthenticated`, creates a BigQuery connection,
465
+ lets the connection's service account invoke the service, and creates the two
466
+ functions in `DATASET`. Every name starts with `PREFIX` (default `causilo`).
467
+ A repository, secret, bucket, service account or connection of that name that
468
+ exists already is reused; what the script creates carries the label
469
+ `causilo_db=deploy` (on a service account and the connection, the description
470
+ "Created by causilo-db bigquery/deploy.sh"). `bigquery/teardown.sh` with the
471
+ same settings drops the two functions and deletes only the pieces that carry
472
+ the mark, with the grants of the service accounts it deletes; it names what it
473
+ keeps. The dataset and its tables are kept unless `DELETE_DATASET=1`. A
474
+ deployment made before the script marked what it created has no marks:
475
+ `FORCE=1` deletes every piece named after `PREFIX`, whoever created it, after
476
+ you type the project id.
477
+
478
+ Who can reach what:
479
+
480
+ - the service reads and writes as its own service account, not as the person
481
+ running the query. It may use only the datasets in `ALLOWED_DATASETS`
482
+ (default `PROJECT.DATASET`), on which it is granted BigQuery Data Editor,
483
+ and it refuses table names outside them. Dataset names are compared exactly,
484
+ as BigQuery treats them (case-sensitive); project ids in any case;
485
+ - anyone who can call the function can therefore have any table in those
486
+ datasets predicted and write new tables into them, and spends the key.
487
+ Calling needs access to the function's dataset and BigQuery Connection User
488
+ on the connection;
489
+ - the caller chooses the id column, and the output table copies it for every
490
+ predicted row. So a caller can copy any column of any table in
491
+ `ALLOWED_DATASETS`, for the rows whose target is blank, into a new table in
492
+ those datasets. Put in `ALLOWED_DATASETS` only datasets whose tables every
493
+ caller may read in full, and that every caller may create tables in;
494
+ - only the connection's service account may invoke the Cloud Run service.
495
+
496
+ What the service does about BigQuery calling more than once. BigQuery may send
497
+ the same call again, even after a success, in the same request or at the same
498
+ time in another one, and retries some failures:
499
+
500
+ - the service claims the output table by creating it, empty, before it
501
+ predicts, with a fingerprint of the call in the table description. Of several
502
+ copies of one call only one predicts; the others wait for it and return its
503
+ summary. A copy that comes later finds the finished table and returns the
504
+ same summary without predicting again. So rerunning the same query costs
505
+ nothing; to predict again, drop the output table;
506
+ - the fingerprint includes the source table's last-modified time, and a
507
+ view's definition. Once the source has changed, the same query is refused
508
+ with "output table already exists" rather than answered with the earlier
509
+ summary; drop the output table to predict from the new data. A view's
510
+ fingerprint does not change when only the tables under it do;
511
+ - an output table that exists for any other reason is refused before anything
512
+ is paid for;
513
+ - once a prediction may have been paid for, a failure (writing the table, a
514
+ timeout, or a later call failing when a large table is sent in several
515
+ calls) fails the query and is not retried. The empty output table is kept,
516
+ marked as failed, so that a copy of the call fails at once instead of
517
+ predicting again; drop it before running again. If the rows were written but
518
+ the table's description could not be updated, the query succeeds and a copy
519
+ finds the rows and does not predict again.
520
+
521
+ Limits: a call has at most 20 minutes, BigQuery's limit for a remote call to
522
+ Cloud Run, and the service is deployed with the same timeout. Source tables
523
+ over 1,000,000 rows are refused (`CAUSILO_MAX_SOURCE_ROWS`), and the service
524
+ runs one call at a time per instance with 2 CPUs and 4 GiB of memory, at most
525
+ `MAX_INSTANCES` (default 3) instances. BigQuery runs at most ten queries with
526
+ remote functions at a time per project. Remote function results are never
527
+ cached, so every query reaches the service; the fingerprint is what keeps a
528
+ rerun free.
529
+
530
+ ## Tested
531
+
532
+ Run against the live API in November 2026 with the two
533
+ [example tables](https://github.com/nums-ai/causilo-db/blob/main/examples/README.md),
534
+ part of the answers hidden. On the command-line rows the predictions were
535
+ written to a table with `--out`, read back and scored against the hidden
536
+ answers (`scripts/live_check.py` does this), and on the BigQuery remote
537
+ function row the table the function wrote was read back the same way
538
+ (`scripts/bigquery_live_check.py`); on the other rows the returned result was
539
+ scored.
540
+
541
+ | Database | Path | Regression, concrete strength (229 cells) | Classification, car trim (385 cells) |
542
+ |---|---|---|---|
543
+ | PostgreSQL 16 | command line | R² 0.939 | accuracy 73.5% |
544
+ | PostgreSQL 16 | `causilo.predict` function | R² 0.939 | accuracy 73.5% |
545
+ | PostgreSQL 17, http extension 1.6.1 | `causilo.predict` function without Python (`install_http.sql`) | R² 0.939 | accuracy 73.5% |
546
+ | MySQL 8.4 | command line | R² 0.939 | accuracy 73.5% |
547
+ | MariaDB 11 | command line | R² 0.939 | accuracy 73.5% |
548
+ | SQL Server 2022 | command line | R² 0.939 | accuracy 73.5% |
549
+ | Oracle 23ai Free | command line | R² 0.939 | accuracy 73.5% |
550
+ | ClickHouse | command line | R² 0.939 | accuracy 73.5% |
551
+ | Trino (memory catalog) | command line | R² 0.939 | accuracy 73.5% |
552
+ | Redshift Serverless | command line | R² 0.939 | accuracy 73.5% |
553
+ | BigQuery | command line | R² 0.939 | accuracy 73.5% |
554
+ | BigQuery | `causilo_predict` remote function, Cloud Run | R² 0.939 | accuracy 73.5% |
555
+ | Snowflake | command line | R² 0.939 | accuracy 73.5% |
556
+ | Snowflake | `CALL CAUSILO.PREDICT` procedure | R² 0.939 | accuracy 73.5% |
557
+ | Snowflake | Native App, `CALL CAUSILO.CORE.PREDICT` | R² 0.939 | accuracy 73.5% |
558
+ | DuckDB | `causilo_db.duckdb` | R² 0.939 | accuracy 73.5% |
559
+ | Spark 4.3, local | `causilo_db.spark` | R² 0.939 | accuracy 73.8% |
560
+ | Databricks, classic single-node cluster (Runtime 16.4 LTS) | `causilo_db.spark` | R² 0.939 | accuracy 73.5% |
561
+
562
+ The table shows that every path returns the same answer, not that the car
563
+ trim is easy to predict: always guessing the most common class ("lounge") is
564
+ right on 72.5% of the hidden rows, so 73.5% is about four rows better. The
565
+ regression result is the meaningful one.
566
+
567
+ Where the same rows went in, the same numbers came out on seventeen paths across
568
+ twelve databases; the PL/pgSQL function's 229 predicted strengths and 385
569
+ predicted trims were identical, row for row, to the command line's on the same
570
+ tables. The small differences elsewhere come from the rows the model
571
+ saw: a table read without ORDER BY can come back in another order (a second
572
+ Redshift run gave 73.2%), and local Spark ran on its own split (73.8%). Spark
573
+ also predicted 1,000 cells of a 300,000-row synthetic table (R² 0.997),
574
+ sampling the filled rows inside Spark.
575
+
576
+ On Databricks the result was checked as a DataFrame; writing it with
577
+ `predict_table(..., output_table=)` has not been run there.
578
+
579
+ `scripts/live_check.py <url>` repeats the database check on any SQLAlchemy URL;
580
+ `--function` checks the installed `causilo.predict` of a PostgreSQL instead,
581
+ and `scripts/bigquery_live_check.py <project> <dataset>` repeats it through a
582
+ deployed BigQuery remote function. Sending the same call again, and three
583
+ copies of a new call in one query, wrote no second result and made no second
584
+ prediction (one prediction per output table in the service log).
585
+
586
+ ## Tests
587
+
588
+ Python 3.11 or later:
589
+
590
+ ```bash
591
+ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
592
+ .venv/bin/python -m pytest -q
593
+ ```
594
+
595
+ They use a fake client and SQLite, DuckDB and a local Spark session (skipped
596
+ without pyspark or Java); nothing reaches the network, even with
597
+ `CAUSILO_API_KEY` set. `tests/test_postgres_http.py` runs `install_http.sql`
598
+ in a PostgreSQL you name with `CAUSILO_TEST_PG_HTTP` (it is skipped otherwise)
599
+ against a stand-in API on 127.0.0.1, and checks that the Parquet tables sent
600
+ and the rows returned are the ones `install.sql` would produce; its docstring
601
+ says how to start the container. `scripts/live_check.py` calls the real API and is
602
+ charged like any other call.
603
+
604
+ See also the [changelog](https://github.com/nums-ai/causilo-db/blob/main/CHANGELOG.md)
605
+ and the [security policy](https://github.com/nums-ai/causilo-db/blob/main/SECURITY.md).
@@ -0,0 +1,12 @@
1
+ causilo_db/__init__.py,sha256=VxUth42QAUPezQKsqxWS4QoIy0j3V07i05jhchVEgL4,366
2
+ causilo_db/cli.py,sha256=e8i4-ylP_MZz9WE6r7AAIn3bWWtyODZ4NHXsyR4wTkQ,4132
3
+ causilo_db/core.py,sha256=6_DpTlhUQMCqAtrIGkUFND9PFiaQnaWKT2UCxeDrlHw,15887
4
+ causilo_db/duckdb.py,sha256=uG_ICdE-xWoEdUoTsPFF7bFN0MljaTvy0AS0wHEnDKk,1772
5
+ causilo_db/spark.py,sha256=SoifLUu4GajcdyeUgn4YxbSs_ZgjUsNZaz9RcB-ycHY,5979
6
+ causilo_db/sql.py,sha256=LdJzE_fscEeq3qDn-3j8vZfmEmWA9CbX_56yR8xwLCw,9311
7
+ causilo_db-0.2.0.dist-info/licenses/LICENSE,sha256=bQq4cZtf5IHpPIwghQ44bAS7lmQTxj5P6Pj3ay8r0yQ,11343
8
+ causilo_db-0.2.0.dist-info/METADATA,sha256=keSZsaF7FFkocpVSTnSySjvLytWA8dC5SCzb9d4fPWc,32807
9
+ causilo_db-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ causilo_db-0.2.0.dist-info/entry_points.txt,sha256=iOfQNCFG-zZwlSJhSzMSNhUG460VElK4gzWiFsKqWDs,51
11
+ causilo_db-0.2.0.dist-info/top_level.txt,sha256=tNlLcgHEZGGPTpHdvKxv00kuBXZrHXqtDYhEbtHLgl4,11
12
+ causilo_db-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ causilo-db = causilo_db.cli:main