classifyre-cli 0.9.0__py3-none-any.whl → 0.9.2__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: classifyre-cli
3
- Version: 0.9.0
3
+ Version: 0.9.2
4
4
  Summary: Classifyre CLI — scan data sources for personal data and secrets
5
5
  License: MIT
6
6
  Keywords: data,governance,masking,pii,secrets
@@ -1,6 +1,6 @@
1
1
  src/__init__.py,sha256=a9znVQMuKTEdH6nB8kUs7jMmPV1U6IFXDzCU5RnzxFo,23
2
2
  src/config.py,sha256=c4v6RbUQuWNIaCySaL5isNmBcUnYZimaHBW7Ki2InpU,2688
3
- src/main.py,sha256=gkxe5_EWFGirt7F4fhb4kTCa6tR8IeHuqo4OVqk-ybk,61980
3
+ src/main.py,sha256=o3wOgXGXbOEkcMq5Dk4wwLUqPzBOKZFNwURiwx9Ei6w,62277
4
4
  src/telemetry.py,sha256=fbSmuJ_t-kSthfIh3E7ESVkloH22kzl8lQKY370YtuU,3089
5
5
  src/augmentation/__init__.py,sha256=pfb4zDjcyo62kHtvRl9QJ-xV28K0A_DTT_kJoF559Lc,147
6
6
  src/augmentation/contract.py,sha256=V0XQn7gk--vRSFTt7f5nC2fh8568KQR_oZ2hg3Tf20I,2716
@@ -62,16 +62,17 @@ src/notebook/__init__.py,sha256=IbgAR0i8AKkvBn9QFPwOy5iJUUeDk-Vkcnhoz2nSHBc,985
62
62
  src/notebook/child.py,sha256=7ZXQ6dBwonPahl2g_tXmlSa-XiXUlBgGJwCU60BA7-U,8944
63
63
  src/notebook/cli.py,sha256=jrfvd3ffktleIhHZb7-dm-3bUiaMBfoYiXcfYSIaQ2I,14925
64
64
  src/notebook/cohort.py,sha256=L2bcx5cvYeBHfJBboQPh2Bw9hsRDBhZ4GUwCieIUKP4,7137
65
- src/notebook/contract.py,sha256=zOv_LhO-MZrpjqP9-gmYuTCJibOj2a4Zf2nfw6IXGiU,10628
65
+ src/notebook/contract.py,sha256=xPEyKD_r7jYdTXAmaIOeeQUgz9DeAqX7wZaKbewquHM,12290
66
66
  src/notebook/execute.py,sha256=pfkphtwWxmGsJtnJzcXwqBtFx-c8feH9oyl7X_Yb7Uk,21019
67
67
  src/notebook/files.py,sha256=3Ef1r_udTM1k8AKNL-wlE135Bczo6Er_s8a90IZ1xUI,6584
68
68
  src/notebook/groups.py,sha256=bl4Rqc4ubjI7kuUCSKAQBTwswtHZlpipFuLh8vc4irU,4366
69
69
  src/notebook/outputs.py,sha256=GcfnUYitRwrfZlrZ_qPNuNhHwtqxl9_UXSX4VT1cIgI,5194
70
70
  src/notebook/packages.py,sha256=mkxFOSmQNja7eqSpXkpe1LesPYfb7MmMt11kkR0QRCU,5827
71
71
  src/notebook/protocol.py,sha256=X9T5zkyh1YEw_bUtvD-GVaF4v4s1ZgBQUI-MSql1hEY,9277
72
+ src/notebook/query.py,sha256=t0Ln4S3tR-28VItGSXpKqlKEBSTYa3kYwU1UsMDoGCY,17198
72
73
  src/notebook/redact.py,sha256=OYp7ugsmIuscgW6oJFb-K-HxQlUI3sSkeR3IkqAt_2o,981
73
74
  src/notebook/scaffold.py,sha256=_vDjiuJEbCIc-4HAa19y9zQ8RU69oMEWaWNchWa62Jw,2283
74
- src/notebook/sdk.py,sha256=6UOp96dOijhUVGngqQop73OUykZ4ykETLt-twNxB790,73498
75
+ src/notebook/sdk.py,sha256=BkZFPO2jZU_FLI6FMJ2jdm5-Ct87ue3Bx-DOWlTSe7c,74104
75
76
  src/notebook/serialize.py,sha256=2OxhXDUmQDyYoNpo1tHq0yhLZhx9UdZlnfjMPJQ54vA,4197
76
77
  src/outputs/__init__.py,sha256=41SESY2nC1y4zF0CTWn1dnTh9AK7qMdRxmRSN_GuWss,126
77
78
  src/outputs/base.py,sha256=uMc0_o2FhA9Y8wlwpg75ljHaXIkF-Yh_frZcPNZVcMo,4962
@@ -92,13 +93,28 @@ src/pipeline/scan_cache.py,sha256=cje5Fcbf2vJDOd3DOoTT__gn28fxQp_HojZESnhr2_s,30
92
93
  src/pipeline/text_artifact.py,sha256=7gpu1r6Ipc0nAt4S8bdzcy8KV9JKaTRgHPgrMw7J1I8,2433
93
94
  src/pipeline/worker_pool.py,sha256=Yjr_2LXxV2nYNcXNN4gFRPK9KN15GP_IkkAzaplKaTc,10543
94
95
  src/query/__init__.py,sha256=RhfyfKL7loabux082s5CMWFlBTq3rDl3q23LwpurAO0,989
95
- src/query/bindings.py,sha256=IdyIZlVxxf-saeRwQ1h5CNivB2PrFFNbTpvuHHmgkwQ,23532
96
+ src/query/bindings.py,sha256=82dFeL_xLcOatt5n-F6wU_WALfTMn_h9o216xjsCsx8,5842
96
97
  src/query/describe.py,sha256=oJBA2WruLYWXROHHlg2Y_P9T6KtWyATUiYbx2T8KoSw,3245
97
- src/query/gate.py,sha256=NkefPhZQqjnvrShSLF2o1FaES7LClpaEtSCfzhg5M6Q,11117
98
+ src/query/gate.py,sha256=cNvdANq3cvcc9AGE-wk2Ad_1HpsZKphUNBscCTga-eM,13040
98
99
  src/query/masks.py,sha256=_pe64ldh6u92JKUhnYzEZqrtxrrahMwA5SHUVQ-jiEA,8959
100
+ src/query/predicate.py,sha256=VH4U3UyfAL5aWKdcrSSgADy5T3s7WVWJowmNywo6EaE,1644
99
101
  src/query/rows.py,sha256=JcUgThkVIKJsQIlhemT_xQ0aiQNItCQ-x8NsLx0KLhc,4588
100
- src/query/runner.py,sha256=OdGG6a-6eLucqNhuPZ2B9WPpDpjtuPN4Wy2gDxqAFKU,6805
101
- src/query/session.py,sha256=EVW-udR3PLQ-E9kiOFIuAcDyYR5yzdp_MnAn60PhlzM,27733
102
+ src/query/runner.py,sha256=Azp3PMVMQCwXIsgku8FDiuCmDgzViltrqksutbd8Bvg,7804
103
+ src/query/session.py,sha256=zUYfPUaN9IP2VcLdzGnU24jlRX66pSc8n7u-_IonCTA,35451
104
+ src/query/warm.py,sha256=Fq9x6Oej51ezywmRvoDUwYJKfHwZMmRBul4JJ01N8oo,7268
105
+ src/query/worker.py,sha256=HG2qbuIApSpQWIuAuXZ60fvgih-_vQCrWdvgBf0Bb3U,39886
106
+ src/query/connectors/__init__.py,sha256=e8rZ-xjwo4qewUMzdwAl5yifTY0sPpUGFaWyYeB48R4,4669
107
+ src/query/connectors/arrow.py,sha256=psnqGJZXNx0Riyl4yhGQ9hayIxMrqaDA-7aplEz7YLc,22760
108
+ src/query/connectors/attached_catalog.py,sha256=KrxLIAGvHsLFjEoGg4KI28wuealjHYDjld4a1UM2vYg,1516
109
+ src/query/connectors/base.py,sha256=GITqFUBomhi-v6tJXmKhEbKXM8p2DKxLDd9y_0wBcac,7402
110
+ src/query/connectors/custom.py,sha256=BLAWAsjXjRMKN58nYhxABdSCCviAUid1hFSkx1xgKYM,4313
111
+ src/query/connectors/databricks.py,sha256=Cvlke_yM72iUO6RB8H-i6duRxiOiTpwbQJsFIJia90c,2757
112
+ src/query/connectors/meilisearch.py,sha256=_mpeFJ_Nn1eIaz6BHm6viOY1ioQahYNxNkV5eKIrPow,8909
113
+ src/query/connectors/mysql.py,sha256=7QyYY35yt_-oRsaWrhLz-7O7zCiSrZqyw-EW2veu1cw,5598
114
+ src/query/connectors/neo4j.py,sha256=leGRZ-uH4Ba2G3yp2mYx8Jouao7nmu5E3B9jUjO8MXk,8533
115
+ src/query/connectors/object_storage.py,sha256=RuOGCQcbUj3u0MtlOPts4VoaxArbFIDdDbcdWsc6FDM,5003
116
+ src/query/connectors/odbc.py,sha256=7wD-rMtzK4svC6mdoP74fLVqM3NPCR7me9DTl5Q1eX0,2717
117
+ src/query/connectors/postgres.py,sha256=pOvVxToZCTs2oE3KW1f0lvjo2Br0_NTl9Nj3VX7TYkQ,2916
102
118
  src/sources/__init__.py,sha256=wYksO_0IcvlGXLouWapKyqzL0jG0El4rDDGRfwa4Zqk,3350
103
119
  src/sources/asset_metadata.py,sha256=OnHwnUSlT1Ow_6Rz2SnJvZyJvaz00TsuQgAnXjTXsdA,6143
104
120
  src/sources/atlassian_common.py,sha256=oi8Eoq9pEaLBXXgnrSzohwXDxlWyZmMtMgNHfB3kMkA,11605
@@ -121,8 +137,8 @@ src/sources/confluence/__init__.py,sha256=VnD7SbvheqWwXS0bgxo9M561UOKgjENkwngwlL
121
137
  src/sources/confluence/source.py,sha256=ngY_RtkHD0pLZbQokPUp580kOnCIl0c-3v_AJmW9ZzM,29043
122
138
  src/sources/custom/__init__.py,sha256=LeFb8IS8gGSDVZ710S0GcmDeau31fvPHg3GroIzuU_4,61
123
139
  src/sources/custom/env.py,sha256=bO82OJVRQ5x8a1AK6jYh5UXS7CG9qodWrxxX6H9xPvU,2543
124
- src/sources/custom/runner.py,sha256=ShOuSOHIgEQgmtoTM6pSPO1I9R3Hx6scHqvptq6-4YM,17995
125
- src/sources/custom/source.py,sha256=7wlGnqdgfQekQmRZp534tdTuTpz31o2ZsANSUbomQG8,52334
140
+ src/sources/custom/runner.py,sha256=9GvuxSMQfeketZBBfJ2AfXqNqPxdpZLVw7LDtDm-LIQ,22091
141
+ src/sources/custom/source.py,sha256=XA_OnfUQTY4XVcFIKNzXDmlc5EZne_uaJSueaTWjl4E,58775
126
142
  src/sources/databricks/__init__.py,sha256=yZZxIF-qhpt_W_zksFQoJGBqaIA40vQCyYLFSksGRFM,69
127
143
  src/sources/databricks/source.py,sha256=9yXuXlkxrk8W4VZLGG6jdWcLdnkiHd5-FpF4wLKvRyg,53030
128
144
  src/sources/dremio/__init__.py,sha256=qIDDLY7WK1lMIU2hGbLxRE_uPLN8-Ksb0FHuwmBZTlw,61
@@ -155,9 +171,9 @@ src/sources/kafka/__init__.py,sha256=BJoJs6vgviCpcyJXuUf70i46XqRnBrqcT9dJJZtHC5o
155
171
  src/sources/kafka/rest.py,sha256=O-txNHNmmXgJTwUzU55nJNEvpEw14sTtUiJaqujkrt4,9539
156
172
  src/sources/kafka/source.py,sha256=KRVYRdSZcQDzJVeKr3O18C3mWgukia07YSuETiZNjVk,40515
157
173
  src/sources/local_folder/__init__.py,sha256=WYo83Wg7ONugPZzisjwPkaWe0TADD7AetTpSXs2k908,71
158
- src/sources/local_folder/source.py,sha256=Nos_mrYYO5iNK-DV2AEv44tD2LzWMXl7awS0br4Iw5g,11164
174
+ src/sources/local_folder/source.py,sha256=7zLU5ZHWYoGot1oPGrJwQJyMpwti2D-O82VBKpXwtXc,11431
159
175
  src/sources/meilisearch/__init__.py,sha256=2ZESbCcM68x8B7qF_bRUt0Aah32pdzje_YndSHizAjM,71
160
- src/sources/meilisearch/source.py,sha256=O2FYVnPYginrDlAxB10Ua5IAjWeOIjjuH93wL0Z61n4,14722
176
+ src/sources/meilisearch/source.py,sha256=FA1aL0WUwh1SocqCsDSHh-B1jlgmHuk-w8wrugJDwKQ,15818
161
177
  src/sources/microsoft_365/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
162
178
  src/sources/microsoft_365/source.py,sha256=cQfuldXqe9icEN0m06WDUtXzYD9EssFZUUiyh1IxL6c,39950
163
179
  src/sources/mongodb/__init__.py,sha256=IcSTuVMB3JOXAjYpwFcFvRuc2a7m6xgZ1VG5AfM4eJU,63
@@ -167,7 +183,7 @@ src/sources/mssql/source.py,sha256=NpsKGZSjoENEvekNZ5BW2WJz6d2DAR24Qp3RsPN_wVQ,2
167
183
  src/sources/mysql/__init__.py,sha256=V0hGtrFJLjGpc3iXzt2k8fH0WzAnyuuDG_2FogcwJBE,59
168
184
  src/sources/mysql/source.py,sha256=r-VtJeGHjGCTimK3ZcCC9iXHETeaYm_F7XmyhebKHIU,16351
169
185
  src/sources/neo4j/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
170
- src/sources/neo4j/source.py,sha256=Fp2qXNJcMrG5TobzF1qNeLRK0ExoDH056Pd-nZ4LMzA,20334
186
+ src/sources/neo4j/source.py,sha256=NcGbW_aj2A3rjAW_InOD6QwqFctP1StWYw9qKi7ChGA,26968
171
187
  src/sources/notion/__init__.py,sha256=FIOPK4itaRGa449jBpvRQd_qlJPPRsjIhSoUBUnMem0,61
172
188
  src/sources/notion/client.py,sha256=Wu-JSXI9KnDgfRUzzP8Vm-_TbhY2FDHdEID_Z-EcMd8,8262
173
189
  src/sources/notion/source.py,sha256=vaqWGVDtdlBAbuhI2vBf3zRQIG56-9C7_yBuflM1DS8,38218
@@ -209,7 +225,8 @@ src/utils/__init__.py,sha256=qHkwUQnAipyD7orncfDbJCaQ47mc02h90FgWy9ad_2o,25
209
225
  src/utils/archive_extraction.py,sha256=0-RZV7CzoMDHWUJtqAU3LCt75mFWDKeSoGFw_wDdIFQ,10657
210
226
  src/utils/content_extraction.py,sha256=Pqm_qMID2mQH1zc8099fNl-xIaQi3hOxQPWzK3yoKac,3082
211
227
  src/utils/dependency_groups.py,sha256=RhgAwooD_4Hk6rfmpQmEYfGx7V-Bkt00UcMeNARFmRU,3508
212
- src/utils/duckdb_engine.py,sha256=EHBOhIQLS8FEYWMhtEYvawgt12i5N_DaaPHbIFWC-34,10660
228
+ src/utils/document_columns.py,sha256=fm6lu-UQM8zr-tKsVhsoxMNarvaJDNx1vVnz1NYtfVM,3081
229
+ src/utils/duckdb_engine.py,sha256=RunGvCvfiKJA45YP7aW9XRBvGCHuZxrTXh3U8a9e05Q,11172
213
230
  src/utils/embedded_files.py,sha256=zXAJr_OAsZD4iI6MUuAuD1x7awvh7n91Ez4pUSmhxnY,25296
214
231
  src/utils/external_video.py,sha256=xnp071RpBFX0xhsnUXxRlY3IKg7DsE4sH0w6B4c_e_k,11695
215
232
  src/utils/file_metadata.py,sha256=wrvabM3tCj0Ii5773NLTAT3z_tpLT8YgqwJym0SIWBI,9892
@@ -220,6 +237,7 @@ src/utils/lakehouse_layout.py,sha256=EilfOlOfrTAF2fn0S6v2_EM_eoYEtqt5Ja-1E7QSM24
220
237
  src/utils/lakehouse_storage.py,sha256=r8ltJypHVoZpr7Jry32oW_R-20nF2zW5qle5YPUrzRo,8115
221
238
  src/utils/lakehouse_tables.py,sha256=Hb4gkoV4jDFmGSeCTXv968wedtpZPM-Sta2pQwu01R8,19751
222
239
  src/utils/legacy_office.py,sha256=LCDiU7E-ZUxHgtQieihQWCXNXOtjiUpJEExWjme-dPI,9205
240
+ src/utils/local_roots.py,sha256=08metnCf50k7zUiI0eCiqzKbkLCFUD67snm0uDysI-Q,3433
223
241
  src/utils/odbc_connection.py,sha256=7zbw2U9nNAZAEZ6DPu0VCMBDkq21e0fWNmyzuKgOeaQ,8505
224
242
  src/utils/payload.py,sha256=ewvSABOLSiIGnrq5A9wfOeFZnVJ_TXtSmEOxDYcE58U,6159
225
243
  src/utils/range_reader.py,sha256=tIT4oicfPT4B_hJyijVmB-SA8-HOj4Gol0Fv0Crw6s0,8661
@@ -233,10 +251,10 @@ src/utils/table_files.py,sha256=NbjlLKJr-y_ANFeQbF0OfFgP1oTCdlu6tIp30gDzZJA,3190
233
251
  src/utils/torch_runtime.py,sha256=79NYfvJ7fjHGgeLXX8rK63qJFuO2Gao1jjRAQ4nicrk,2527
234
252
  src/utils/transcription.py,sha256=WOitCBNTZ7rrGq41ZGH99XmAIyqxvqmnJHxbK3RP7Rs,16943
235
253
  src/utils/urn.py,sha256=gqSl0H0FBZZ3cJbpDWX1ewGcyZz2MrNVTIQdoFrQMM0,12622
236
- src/utils/uv_sync.py,sha256=VZ0TZ7t3_pSjxOb20BxUs2XLVjigXnVqa5y69XWlnE8,9307
254
+ src/utils/uv_sync.py,sha256=L4ETHuidlgFLbz4e3Vv0Ornh7w8xrkYeFQQGw0hJe8E,10214
237
255
  src/utils/validation.py,sha256=5NHsgyZwyEONRu9_ADxUAQNPvbMnpMhKL-hpgFEVMm8,3837
238
256
  src/utils/video_processing.py,sha256=B6Br9ybFEa_ioglJGo0P9Fmp1e2B95C24joAktwrjww,11293
239
- classifyre_cli-0.9.0.dist-info/METADATA,sha256=IpRJd_dgmHp-QzhVhI-TMGWeRAa6XvRqqg_BuBl9NG0,5841
240
- classifyre_cli-0.9.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
241
- classifyre_cli-0.9.0.dist-info/entry_points.txt,sha256=edxllyMiIFfajgCZ3dTRACXYGC34ZX1AYTezMSR5E_8,45
242
- classifyre_cli-0.9.0.dist-info/RECORD,,
257
+ classifyre_cli-0.9.2.dist-info/METADATA,sha256=CsmcURnldweB6Kt6C_UJzskmp6nIntK7l3f2ZbCHq9Q,5841
258
+ classifyre_cli-0.9.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
259
+ classifyre_cli-0.9.2.dist-info/entry_points.txt,sha256=edxllyMiIFfajgCZ3dTRACXYGC34ZX1AYTezMSR5E_8,45
260
+ classifyre_cli-0.9.2.dist-info/RECORD,,
src/main.py CHANGED
@@ -1168,6 +1168,12 @@ def main() -> None:
1168
1168
  from .query.runner import run_query_command
1169
1169
 
1170
1170
  sys.exit(run_query_command(sys.argv[2] if len(sys.argv) > 2 else None))
1171
+ if len(sys.argv) > 1 and sys.argv[1] == "query-worker":
1172
+ # The warm host for the same queries (src/query/worker.py): it imports
1173
+ # what a query needs once, in its fork server, not here.
1174
+ from .query.worker import run_worker_command
1175
+
1176
+ sys.exit(run_worker_command())
1171
1177
  from .telemetry import init_telemetry
1172
1178
 
1173
1179
  init_telemetry()
src/notebook/contract.py CHANGED
@@ -25,7 +25,18 @@ from .serialize import ModuleSource, cell_id_of, to_module_source
25
25
  REQUIRED_FUNCTIONS = ("test_connection", "extract")
26
26
 
27
27
  #: Implemented when the source can support them; absence is not an error.
28
- OPTIONAL_FUNCTIONS = ("discover", "fetch_content", "relationships", "augment_sources")
28
+ OPTIONAL_FUNCTIONS = (
29
+ "discover",
30
+ "fetch_content",
31
+ "relationships",
32
+ "augment_sources",
33
+ "tables",
34
+ "scan",
35
+ )
36
+
37
+ #: SQL queries read a notebook's tables live: ``tables()`` declares them and
38
+ #: ``scan(table, request)`` reads one (docs/prd/QC-query-connectors.md §5.8).
39
+ QUERY_FUNCTIONS = ("tables", "scan")
29
40
 
30
41
  #: A notebook that only enriches other sources has nothing to extract.
31
42
  AUGMENT_ENTRY_POINT = "augment_sources"
@@ -35,6 +46,9 @@ SYNTAX_ERROR = "syntax_error"
35
46
  DUPLICATE_CELL_ID = "duplicate_cell_id"
36
47
  EMPTY_NOTEBOOK = "empty_notebook"
37
48
  NOT_A_FUNCTION = "not_a_function"
49
+ #: ``tables()`` without ``scan()`` or the other way round, or a ``scan`` that
50
+ #: does not take ``(table, request)``.
51
+ QUERY_CONTRACT = "query_contract"
38
52
 
39
53
  #: A later cell rebinds a name an earlier cell defined. A warning, never a
40
54
  #: violation: shadowing is legal Python and occasionally deliberate.
@@ -244,6 +258,8 @@ def validate_module(
244
258
  )
245
259
  )
246
260
 
261
+ violations.extend(_query_violations(functions))
262
+
247
263
  return ContractReport(
248
264
  violations=tuple(violations),
249
265
  defined_functions=frozenset(functions),
@@ -251,6 +267,36 @@ def validate_module(
251
267
  )
252
268
 
253
269
 
270
+ def _query_violations(functions: dict[str, ast.stmt]) -> list[ContractViolation]:
271
+ """``tables()`` and ``scan(table, request)`` come as a pair."""
272
+ defined = [name for name in QUERY_FUNCTIONS if name in functions]
273
+ if len(defined) == 1:
274
+ (present,) = defined
275
+ other = "scan" if present == "tables" else "tables"
276
+ return [
277
+ ContractViolation(
278
+ kind=QUERY_CONTRACT,
279
+ message=(
280
+ f"'{present}()' is defined without '{other}()'. SQL queries read a "
281
+ "notebook's tables with both: tables() declares them, "
282
+ "scan(table, request) reads one."
283
+ ),
284
+ )
285
+ ]
286
+ scan = functions.get("scan")
287
+ if isinstance(scan, (ast.FunctionDef, ast.AsyncFunctionDef)):
288
+ args = scan.args
289
+ positional = len(args.posonlyargs) + len(args.args)
290
+ if isinstance(scan, ast.AsyncFunctionDef) or (positional < 2 and args.vararg is None):
291
+ return [
292
+ ContractViolation(
293
+ kind=QUERY_CONTRACT,
294
+ message="'scan' must be 'def scan(table, request):' (not async).",
295
+ )
296
+ ]
297
+ return []
298
+
299
+
254
300
  def validate_notebook(
255
301
  cells: Iterable[Mapping[str, object] | object],
256
302
  *,
src/notebook/query.py ADDED
@@ -0,0 +1,448 @@
1
+ """SQL over a custom source: what a notebook's ``tables()`` and ``scan()`` see
2
+ (docs/prd/QC-query-connectors.md §5.8).
3
+
4
+ A notebook that defines both is queryable live, like a Meilisearch index: the
5
+ scan records each declared :class:`Table` as a ``table`` asset with its
6
+ columns, and a query that reads one calls ``scan(table, request)`` in the
7
+ notebook's own child process (``src/sources/custom/runner.py``), which
8
+ returns the rows as Arrow. The query engine filters every row again, so what
9
+ ``scan()`` does with the request's filters only decides how much it reads:
10
+ returning more rows than the filters select is always correct, returning
11
+ fewer never is.
12
+
13
+ This module is imported by the notebook runtime (the child) and by the query
14
+ side (the parent); it imports pyarrow only when rows are converted.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ import datetime as dt
21
+ import re
22
+ import time
23
+ from collections.abc import Iterable, Iterator, Mapping
24
+ from dataclasses import dataclass, field
25
+ from decimal import Decimal
26
+ from typing import Any, cast
27
+
28
+ from ..query.predicate import OPS, Op
29
+ from ..query.predicate import Predicate as Filter
30
+
31
+ __all__ = [
32
+ "COLUMN_CLASSIFICATIONS",
33
+ "COLUMN_TYPES",
34
+ "Filter",
35
+ "QueryContractError",
36
+ "ScanCall",
37
+ "ScanRefusedError",
38
+ "ScanRequest",
39
+ "Table",
40
+ ]
41
+
42
+ #: The column types a table may declare (DuckDB names), and ``<type>[]`` lists.
43
+ COLUMN_TYPES = (
44
+ "VARCHAR",
45
+ "BIGINT",
46
+ "INTEGER",
47
+ "DOUBLE",
48
+ "BOOLEAN",
49
+ "DATE",
50
+ "TIMESTAMP",
51
+ "TIMESTAMPTZ",
52
+ "JSON",
53
+ )
54
+ #: What a column may be declared to hold (``Table(classify=...)``), least
55
+ #: guarded first; ``personal`` and ``sensitive`` are masked and ``secret``
56
+ #: hidden for people who do not read the table in clear, as when findings
57
+ #: classify a column. Equal to the API's ``CLASSIFICATIONS`` (governance-rules.ts),
58
+ #: checked by tests/test_query_custom.py.
59
+ COLUMN_CLASSIFICATIONS = ("public", "internal", "confidential", "personal", "sensitive", "secret")
60
+ _TABLE_NAME = re.compile(r"^[a-z_][a-z0-9_]{0,62}$")
61
+
62
+
63
+ class QueryContractError(ValueError):
64
+ """``tables()`` or ``scan()`` broke the contract; the message says how."""
65
+
66
+
67
+ class ScanRefusedError(Exception):
68
+ """Raise it from ``scan()`` to refuse a query with a message of your own.
69
+
70
+ The message is shown to whoever ran the query, so write it for them
71
+ (*"companies needs WHERE fnr = ..."*) and keep values out of it. Any other
72
+ exception fails the query with only its type and line: its text may hold
73
+ the values it was raised over, and goes to the query's log instead.
74
+ """
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class Table:
79
+ """One table a query can read from this source.
80
+
81
+ ``columns`` maps each column to its type: ``VARCHAR``, ``BIGINT``,
82
+ ``INTEGER``, ``DOUBLE``, ``BOOLEAN``, ``DATE``, ``TIMESTAMP``,
83
+ ``TIMESTAMPTZ``, ``JSON`` (objects and lists as JSON text), or a list of
84
+ one of them (``VARCHAR[]``). The table is ``<source>.main.<name>`` in SQL
85
+ (``schema`` picks another middle part).
86
+
87
+ ``classify`` says what a column holds: ``{"birth_date": "personal"}``. A
88
+ query's rows are never scanned for personal data, so this (or a steward)
89
+ is what masks a column by default: ``personal`` and ``sensitive`` are
90
+ masked, ``secret`` hidden, for people who do not read the table in clear.
91
+ """
92
+
93
+ name: str
94
+ columns: Mapping[str, str]
95
+ description: str = ""
96
+ schema: str = "main"
97
+ classify: Mapping[str, str] = field(default_factory=dict)
98
+
99
+ def check(self) -> None:
100
+ for label, value in (("name", self.name), ("schema", self.schema)):
101
+ if not isinstance(value, str) or not _TABLE_NAME.match(value):
102
+ raise QueryContractError(
103
+ f"Table {label} {value!r} must be lower-case letters, digits and "
104
+ "underscores, starting with a letter."
105
+ )
106
+ if not isinstance(self.columns, Mapping) or not self.columns:
107
+ raise QueryContractError(f"Table {self.name!r} declares no columns.")
108
+ for column, kind in self.columns.items():
109
+ if not isinstance(column, str) or not column:
110
+ raise QueryContractError(f"Table {self.name!r} has a column with no name.")
111
+ base = str(kind).strip().upper().removesuffix("[]")
112
+ if base not in COLUMN_TYPES:
113
+ raise QueryContractError(
114
+ f"Column {column!r} of table {self.name!r} has type {kind!r}; "
115
+ f"use one of {', '.join(COLUMN_TYPES)} (or a list, like VARCHAR[])."
116
+ )
117
+ if not isinstance(self.classify, Mapping):
118
+ raise QueryContractError(f"Table {self.name!r}: classify must be a dict.")
119
+ for column, label in self.classify.items():
120
+ if column not in self.columns:
121
+ raise QueryContractError(
122
+ f"Table {self.name!r} classifies {column!r}, which it does not declare."
123
+ )
124
+ if label not in COLUMN_CLASSIFICATIONS:
125
+ raise QueryContractError(
126
+ f"Column {column!r} of table {self.name!r} is classified {label!r}; "
127
+ f"use one of {', '.join(COLUMN_CLASSIFICATIONS)}."
128
+ )
129
+
130
+ def to_dict(self) -> dict[str, Any]:
131
+ return {
132
+ "name": self.name,
133
+ "schema": self.schema,
134
+ "description": self.description,
135
+ "columns": [
136
+ {
137
+ "name": name,
138
+ "type": str(kind).strip().upper(),
139
+ **({"classification": self.classify[name]} if name in self.classify else {}),
140
+ }
141
+ for name, kind in self.columns.items()
142
+ ],
143
+ }
144
+
145
+
146
+ def declared_tables(value: Any) -> list[Table]:
147
+ """What ``tables()`` returned, checked: a list (or iterable) of ``Table``."""
148
+ if isinstance(value, Table):
149
+ value = [value]
150
+ if value is None or isinstance(value, (str, bytes, Mapping)):
151
+ raise QueryContractError("tables() must return a list of Table(...).")
152
+ out: list[Table] = []
153
+ seen: set[str] = set()
154
+ for item in value:
155
+ if not isinstance(item, Table):
156
+ raise QueryContractError(
157
+ f"tables() must return Table(...) objects, got {type(item).__name__}."
158
+ )
159
+ item.check()
160
+ # scan() is called with the name alone, so it is unique across schemas.
161
+ if item.name in seen:
162
+ raise QueryContractError(f"tables() declares {item.name!r} twice.")
163
+ seen.add(item.name)
164
+ out.append(item)
165
+ return out
166
+
167
+
168
+ @dataclass
169
+ class ScanRequest:
170
+ """What the query needs from one ``scan()`` call.
171
+
172
+ Read ``columns`` and ``filters`` to fetch less; call :meth:`values` (or
173
+ :meth:`use`) for the filters you sent to your source, so the person sees
174
+ them under the query as filtered at the source.
175
+ """
176
+
177
+ #: The columns the query reads; None: all of them.
178
+ columns: tuple[str, ...] | None
179
+ filters: tuple[Filter, ...]
180
+ #: More rows than this and the query is refused: stop fetching after it.
181
+ max_rows: int
182
+ #: ``time.monotonic()`` by which the query must be done.
183
+ deadline: float
184
+ used: list[Filter] = field(default_factory=list)
185
+ #: Calls made to the source, shown under the query (``count_request()``).
186
+ requests: int = 0
187
+
188
+ def values(self, column: str) -> tuple[Any, ...] | None:
189
+ """The values ``column`` is limited to by ``column = x`` or
190
+ ``column IN (...)``, or None when the query does not limit it so.
191
+ Marks that filter as used."""
192
+ for item in self.filters:
193
+ if item.column == column and item.op in ("=", "in"):
194
+ self.use(item)
195
+ return tuple(item.value) if item.op == "in" else (item.value,)
196
+ return None
197
+
198
+ def value(self, column: str) -> Any:
199
+ """The value of ``column = x``, or None. Marks that filter as used."""
200
+ for item in self.filters:
201
+ if item.column == column and item.op == "=":
202
+ self.use(item)
203
+ return item.value
204
+ return None
205
+
206
+ def use(self, *filters: Filter) -> None:
207
+ """Say which filters ``scan()`` sent to its source."""
208
+ for item in filters:
209
+ if item not in self.used:
210
+ self.used.append(item)
211
+
212
+ def count_request(self, n: int = 1) -> None:
213
+ """Count calls made to the source (shown with the query's result)."""
214
+ self.requests += n
215
+
216
+ def seconds_left(self) -> float:
217
+ """Time left before the query is stopped; give each call at most this."""
218
+ return max(0.0, self.deadline - time.monotonic())
219
+
220
+
221
+ # ── the wire between the query (parent) and the notebook (child) ───────
222
+
223
+
224
+ @dataclass(frozen=True)
225
+ class ScanCall:
226
+ """One ``scan()`` the query asks the notebook for (the ``scan`` command)."""
227
+
228
+ table: str
229
+ #: The table's declared columns, ``(name, type)``: the batches' schema.
230
+ columns: tuple[tuple[str, str], ...]
231
+ #: The columns the query reads (None: all), what ``request.columns`` says.
232
+ projection: tuple[str, ...] | None
233
+ filters: tuple[Filter, ...]
234
+ max_rows: int
235
+ seconds_left: float
236
+
237
+ def to_wire(self) -> dict[str, Any]:
238
+ return {
239
+ "command": "scan",
240
+ "table": self.table,
241
+ "columns": [list(c) for c in self.columns],
242
+ "projection": list(self.projection) if self.projection is not None else None,
243
+ "filters": encode_filters(self.filters),
244
+ "maxRows": self.max_rows,
245
+ "secondsLeft": self.seconds_left,
246
+ }
247
+
248
+ @classmethod
249
+ def from_wire(cls, raw: Mapping[str, Any]) -> ScanCall:
250
+ projection = raw.get("projection")
251
+ return cls(
252
+ table=str(raw.get("table") or ""),
253
+ columns=tuple((str(n), str(t)) for n, t in raw.get("columns") or ()),
254
+ projection=tuple(str(c) for c in projection) if isinstance(projection, list) else None,
255
+ filters=decode_filters(raw.get("filters")),
256
+ max_rows=int(raw.get("maxRows") or 0),
257
+ seconds_left=float(raw.get("secondsLeft") or 0),
258
+ )
259
+
260
+
261
+ def encode_value(value: Any) -> Any:
262
+ """A filter value as JSON: dates and decimals tagged, the rest as is."""
263
+ if isinstance(value, tuple):
264
+ return [encode_value(v) for v in value]
265
+ if isinstance(value, dt.datetime):
266
+ return {"$datetime": value.isoformat()}
267
+ if isinstance(value, dt.date):
268
+ return {"$date": value.isoformat()}
269
+ if isinstance(value, Decimal):
270
+ return {"$decimal": str(value)}
271
+ return value
272
+
273
+
274
+ def decode_value(value: Any) -> Any:
275
+ if isinstance(value, list):
276
+ return tuple(decode_value(v) for v in value)
277
+ if isinstance(value, dict):
278
+ if "$datetime" in value:
279
+ return dt.datetime.fromisoformat(str(value["$datetime"]))
280
+ if "$date" in value:
281
+ return dt.date.fromisoformat(str(value["$date"]))
282
+ if "$decimal" in value:
283
+ return Decimal(str(value["$decimal"]))
284
+ return value
285
+
286
+
287
+ def encode_filters(filters: Iterable[Any]) -> list[dict[str, Any]]:
288
+ return [{"column": f.column, "op": f.op, "value": encode_value(f.value)} for f in filters]
289
+
290
+
291
+ def decode_filters(raw: Any) -> tuple[Filter, ...]:
292
+ out: list[Filter] = []
293
+ for item in raw or ():
294
+ if not isinstance(item, dict) or not isinstance(item.get("column"), str):
295
+ continue
296
+ op = next((o for o in OPS if o == item.get("op")), None)
297
+ if op is not None:
298
+ out.append(Filter(item["column"], cast(Op, op), decode_value(item.get("value"))))
299
+ return tuple(out)
300
+
301
+
302
+ def batch_to_wire(batch: Any) -> str:
303
+ import pyarrow as pa
304
+
305
+ sink = pa.BufferOutputStream()
306
+ with pa.ipc.new_stream(sink, batch.schema) as writer:
307
+ writer.write_batch(batch)
308
+ return base64.b64encode(sink.getvalue().to_pybytes()).decode("ascii")
309
+
310
+
311
+ def batch_from_wire(text: str) -> Any:
312
+ import pyarrow as pa
313
+
314
+ reader = pa.ipc.open_stream(pa.py_buffer(base64.b64decode(text)))
315
+ batches = list(reader)
316
+ if len(batches) != 1:
317
+ return pa.Table.from_batches(batches, schema=reader.schema).combine_chunks().to_batches()[0]
318
+ return batches[0]
319
+
320
+
321
+ # ── rows ───────────────────────────────────────────────────────────────
322
+
323
+
324
+ def chunks(result: Any, size: int = 1000) -> Iterator[Any]:
325
+ """What ``scan()`` returned or yielded, as pages: Arrow batches as they
326
+ are, dicts gathered ``size`` at a time."""
327
+ import pyarrow as pa
328
+
329
+ if result is None:
330
+ return
331
+ if isinstance(result, (pa.RecordBatch, pa.Table, Mapping)):
332
+ result = [result]
333
+ page: list[dict[str, Any]] = []
334
+ for item in result:
335
+ if isinstance(item, (pa.Table, pa.RecordBatch)):
336
+ if page: # rows before a batch go first, in order
337
+ yield page
338
+ page = []
339
+ yield from item.to_batches() if isinstance(item, pa.Table) else [item]
340
+ continue
341
+ if isinstance(item, Mapping):
342
+ page.append(dict(item))
343
+ elif isinstance(item, list) and all(isinstance(row, Mapping) for row in item):
344
+ page.extend(dict(row) for row in item)
345
+ else:
346
+ raise QueryContractError(
347
+ "scan() must yield dicts (one per row), lists of dicts, or Arrow "
348
+ f"record batches; got {type(item).__name__}."
349
+ )
350
+ if len(page) >= size:
351
+ yield page
352
+ page = []
353
+ if page:
354
+ yield page
355
+
356
+
357
+ def rows_to_batch(chunk: Any, schema: Any, table: str) -> Any:
358
+ """A page of ``scan()``'s rows as a batch of the declared ``schema``.
359
+
360
+ ISO text in a date or timestamp column is read as a date or timestamp,
361
+ and a ``Decimal`` as a number; any other value of another type than the
362
+ column declares is refused, naming the column (never the value).
363
+ """
364
+ import pyarrow as pa
365
+
366
+ from ..query.connectors.arrow import ConnectorError, to_batch
367
+
368
+ if not isinstance(chunk, pa.RecordBatch):
369
+ chunk = [_coerced(row, schema) for row in chunk]
370
+ elif not chunk.schema.equals(schema):
371
+ missing = [n for n in schema.names if n not in chunk.schema.names]
372
+ if missing:
373
+ chunk = chunk.to_pylist()
374
+ else:
375
+ try:
376
+ chunk = chunk.select(schema.names).cast(schema)
377
+ except (pa.ArrowInvalid, pa.ArrowNotImplementedError, TypeError):
378
+ chunk = chunk.to_pylist()
379
+ try:
380
+ return to_batch(chunk, schema)
381
+ except ConnectorError:
382
+ for f in schema:
383
+ rows = chunk.to_pylist() if isinstance(chunk, pa.RecordBatch) else chunk
384
+ try:
385
+ to_batch([{f.name: row.get(f.name)} for row in rows], pa.schema([f]))
386
+ except ConnectorError:
387
+ raise QueryContractError(
388
+ f"scan() returned a value for {table}.{f.name} that is not "
389
+ f"{_type_name(f.type)}, the type tables() declares."
390
+ ) from None
391
+ raise
392
+
393
+
394
+ def _coerced(row: Mapping[str, Any], schema: Any) -> dict[str, Any]:
395
+ """ISO text as dates and timestamps, ``Decimal`` as numbers, and
396
+ timestamps in the zone the column declares (UTC)."""
397
+ import pyarrow as pa
398
+
399
+ out = dict(row)
400
+ for f in schema:
401
+ value = out.get(f.name)
402
+ if value is None:
403
+ continue
404
+ if isinstance(value, Decimal) and (
405
+ pa.types.is_floating(f.type) or pa.types.is_integer(f.type)
406
+ ):
407
+ integral = value == value.to_integral_value()
408
+ out[f.name] = int(value) if pa.types.is_integer(f.type) and integral else float(value)
409
+ elif isinstance(value, str) and pa.types.is_date(f.type):
410
+ try:
411
+ out[f.name] = dt.date.fromisoformat(value[:10])
412
+ except ValueError:
413
+ pass # refused below, naming the column
414
+ elif pa.types.is_timestamp(f.type) and isinstance(value, (str, dt.datetime)):
415
+ if isinstance(value, str):
416
+ try:
417
+ value = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
418
+ except ValueError:
419
+ continue
420
+ out[f.name] = _in_zone(value, utc=f.type.tz is not None)
421
+ return out
422
+
423
+
424
+ def _in_zone(value: dt.datetime, *, utc: bool) -> dt.datetime:
425
+ """A naive timestamp is UTC; a column without a zone gets UTC, naive."""
426
+ if utc:
427
+ return value if value.tzinfo is not None else value.replace(tzinfo=dt.UTC)
428
+ if value.tzinfo is None:
429
+ return value
430
+ return value.astimezone(dt.UTC).replace(tzinfo=None)
431
+
432
+
433
+ def _type_name(kind: Any) -> str:
434
+ import pyarrow as pa
435
+
436
+ if pa.types.is_integer(kind):
437
+ return "an integer"
438
+ if pa.types.is_floating(kind):
439
+ return "a number"
440
+ if pa.types.is_boolean(kind):
441
+ return "a boolean"
442
+ if pa.types.is_date(kind):
443
+ return "a date"
444
+ if pa.types.is_timestamp(kind):
445
+ return "a timestamp"
446
+ if pa.types.is_list(kind):
447
+ return "a list"
448
+ return "text"