rabbit-bq-optimizer-airflow-plugin 1.0.0__tar.gz

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,405 @@
1
+ Metadata-Version: 2.4
2
+ Name: rabbit-bq-optimizer-airflow-plugin
3
+ Version: 1.0.0
4
+ Summary: Airflow 2 plugin for Rabbit BigQuery Job Optimizer
5
+ Home-page: https://github.com/followrabbit-ai/bq-job-optimizer-airflow-plugin
6
+ Author: Rabbit Team
7
+ Author-email: success@followrabbit.ai
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Framework :: Apache Airflow
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: rabbit-bq-job-optimizer>=0.1.18
16
+ Dynamic: author
17
+ Dynamic: author-email
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: home-page
22
+ Dynamic: license-file
23
+ Dynamic: requires-dist
24
+ Dynamic: requires-python
25
+ Dynamic: summary
26
+
27
+ # Rabbit BigQuery Job Optimizer Airflow Plugin
28
+
29
+ This Airflow plugin automatically optimizes BigQuery job configurations using the Rabbit API. It patches the BigQueryHook to intercept job configurations and optimize them before execution.
30
+
31
+ ## Features
32
+
33
+ - Automatically intercepts all BigQuery job submissions
34
+ - Optimizes job configurations via the Rabbit API
35
+ - Routes `BigQueryInsertJobOperator` submits to an on-demand pool billing project when the optimizer sets `optimizedJob.jobReference.projectId`
36
+ - Graceful fallback to original configuration if optimization fails
37
+ - Comprehensive error handling and logging
38
+
39
+ Already running an older version? See [Updating](#updating).
40
+
41
+ ## Installation
42
+
43
+ ### Option A: PyPI (recommended)
44
+
45
+ 1. Add the plugin and client to your Airflow environment:
46
+ - If using `requirements.txt`:
47
+ ```txt
48
+ rabbit-bq-job-optimizer==0.1.18
49
+ rabbit-bq-optimizer-airflow-plugin==1.0.0
50
+ ```
51
+ - If using `constraints.txt`:
52
+ ```txt
53
+ rabbit-bq-job-optimizer==0.1.18
54
+ rabbit-bq-optimizer-airflow-plugin==1.0.0
55
+ ```
56
+ - If using a custom Docker image, add to your Dockerfile:
57
+ ```dockerfile
58
+ RUN pip install rabbit-bq-job-optimizer==0.1.18 rabbit-bq-optimizer-airflow-plugin==1.0.0
59
+ ```
60
+
61
+ The plugin registers via Airflow's plugin entry point — no file copy into `plugins/` is required.
62
+
63
+ 2. Restart your Airflow scheduler, workers, and webserver to load the plugin. If you use deferrable `BigQueryInsertJobOperator`, restart the triggerer as well.
64
+
65
+ ### Option B: Copy into `plugins/`
66
+
67
+ 1. Add the Python client to your Airflow environment dependencies:
68
+
69
+ ```txt
70
+ rabbit-bq-job-optimizer==0.1.18
71
+ ```
72
+
73
+ 2. Copy the plugin file into your Airflow plugins directory:
74
+ ```bash
75
+ cp bq-job-optimizer-airflow-2/rabbit_bq_optimizer_plugin.py "$AIRFLOW_HOME/plugins/"
76
+ ```
77
+
78
+ 3. Restart your Airflow scheduler, workers, and webserver (and triggerer if using deferrable operators).
79
+
80
+ ## Updating
81
+
82
+ ### PyPI install
83
+
84
+ Update to the new package versions in your environment dependencies:
85
+
86
+ ```txt
87
+ rabbit-bq-job-optimizer==0.1.18
88
+ rabbit-bq-optimizer-airflow-plugin==1.0.0
89
+ ```
90
+
91
+ Apply the update using your platform's usual process, then restart Airflow components (including the triggerer if you use deferrable `BigQueryInsertJobOperator`). Your `rabbit_api` connection, `rabbit_bq_optimizer_config` variable, and DAGs are unchanged. If optimization fails, the plugin still submits the original job (fail-open).
92
+
93
+ ### Copy into `plugins/` (optional)
94
+
95
+ If you installed via [Option B](#option-b-copy-into-plugins) and want to stay on the copy method, bump the client version in your environment dependencies and replace `rabbit_bq_optimizer_plugin.py` in your plugins location with the new file from this repo. Then restart Airflow components as above.
96
+
97
+ ### Switching from copy to PyPI
98
+
99
+ If you previously deployed `rabbit_bq_optimizer_plugin.py` to your plugins location and are switching to the PyPI package, **remove that file** — the PyPI install loads via an entry point and the copied file causes duplicate plugin registration. On startup the plugin logs an error if both are present. When the file is writable, you can set `RABBIT_BQ_OPTIMIZER_REMOVE_LEGACY_PLUGIN=true` to remove it automatically on load.
100
+
101
+ For pool billing routing, the Airflow service account also needs `roles/bigquery.jobUser` on the pool billing projects — contact Rabbit support for your project list. See [Pool billing project routing](#pool-billing-project-routing).
102
+
103
+ ## Configuration
104
+
105
+ ### 1. Create the Rabbit API connection
106
+
107
+ For security reasons the Rabbit API key must be stored in an Airflow connection instead of a variable. The plugin expects a connection with ID `rabbit_api`:
108
+
109
+ - `Conn Type`: `Generic` (or `HTTP`)
110
+ - `Conn ID`: `rabbit_api`
111
+ - `Password`: Rabbit API key (required)
112
+ - `Extra` (optional):
113
+ ```json
114
+ {
115
+ "api_base_url": "https://api.followrabbit.ai/bq-job-optimizer"
116
+ }
117
+ ```
118
+ Only include `api_base_url` if you need to override the default Rabbit endpoint; otherwise it will fall back automatically.
119
+
120
+ CLI example:
121
+
122
+ ```bash
123
+ airflow connections add rabbit_api \
124
+ --conn-type generic \
125
+ --conn-password "<your-rabbit-api-key>" \
126
+ --conn-extra '{"api_base_url": "https://api.followrabbit.ai/bq-job-optimizer"}'
127
+ ```
128
+
129
+ ### 2. Set the optimization parameters
130
+
131
+ The remaining optimizer configuration stays in an Airflow variable. Create a JSON configuration with the following structure:
132
+
133
+ ```json
134
+ {
135
+ "default_pricing_mode": "on_demand",
136
+ "reservation_ids": [
137
+ "project:region.reservation-name1",
138
+ "project:region.reservation-name2"
139
+ ]
140
+ }
141
+ ```
142
+
143
+ ### Configuration Fields
144
+
145
+ - `default_pricing_mode` (required): The default pricing mode for jobs. Must be one of: `"on_demand"` or `"slot_based"`
146
+ - `reservation_ids` (required): List of reservation IDs in the format "project:region.reservation-name"
147
+
148
+ ### Setting the Configuration
149
+
150
+ You can set the configuration in two ways:
151
+
152
+ 1. Using the Airflow CLI:
153
+ ```bash
154
+ airflow variables set rabbit_bq_optimizer_config '{
155
+ "default_pricing_mode": "on_demand",
156
+ "reservation_ids": [
157
+ "project:region.reservation-name1",
158
+ "project:region.reservation-name2"
159
+ ]
160
+ }'
161
+ ```
162
+
163
+ 2. Through the Airflow UI:
164
+ - Go to Admin -> Variables
165
+ - Add a new variable named `rabbit_bq_optimizer_config`
166
+ - Paste the JSON configuration
167
+
168
+ ## End-to-End Test Plan
169
+
170
+ ### Local Testing
171
+
172
+ A setup script `setup_local_test.sh` is provided in the root directory to help you spin up a local Airflow environment for testing.
173
+
174
+ **Prerequisites:**
175
+ - Python 3.8-3.12 (Airflow 2.9.1 requirement; the script will automatically detect and use a compatible version)
176
+ - `pip`
177
+
178
+ **Steps:**
179
+
180
+ 1. **Run the setup script:**
181
+ ```bash
182
+ ./setup_local_test.sh
183
+ ```
184
+ This script will:
185
+ - Create a virtual environment (if not present)
186
+ - Install Airflow using the official constraints file plus dependencies from `test_requirements.txt`
187
+ - Initialize the Airflow database
188
+ - Create an admin user
189
+ - Deploy the plugin and test DAG
190
+ - Configure the `rabbit_api` connection (with a dummy key)
191
+ - Configure the `rabbit_bq_optimizer_config` variable
192
+
193
+ *Note: The script installs Airflow using the official constraints file for your Python version so that binary wheels (including `google-re2`) are used. Additional dependencies (`rabbit-bq-job-optimizer`, `apache-airflow-providers-google`, `google-cloud-bigquery`, etc.) are installed with the same constraints to match the Airflow release.*
194
+
195
+ 2. **Run the test DAG:**
196
+ The setup script automatically deploys `test_dag.py` to the DAGs directory.
197
+
198
+ Execute the test DAG:
199
+ ```bash
200
+ source venv/bin/activate
201
+ export AIRFLOW_HOME=$(pwd)/airflow_home
202
+ airflow dags test rabbit_optimizer_test $(date +%Y-%m-%d)
203
+ ```
204
+
205
+ 3. **Verify Results:**
206
+ Check the logs for the following:
207
+ - `Rabbit BQ Optimizer: patching BigQueryHook.insert_job` (scheduler logs at startup)
208
+ - `Rabbit BQ Optimizer: patching BigQueryInsertJobOperator._submit_job` (scheduler logs at startup)
209
+ - `Rabbit BQ Optimizer: optimization result=...` at DEBUG on job submit (or failure if using dummy key/URL)
210
+
211
+ 4. **Run automated tests:**
212
+ After setup, you can run automated tests to validate the plugin:
213
+
214
+ **Test connection loading:**
215
+ ```bash
216
+ source venv/bin/activate
217
+ export AIRFLOW_HOME=$(pwd)/airflow_home
218
+ cd bq-job-optimizer-airflow-2
219
+ python test_plugin_connection.py
220
+ ```
221
+ This verifies that the plugin can load credentials from the Airflow connection.
222
+
223
+ **Test DAG execution (full integration):**
224
+ ```bash
225
+ source venv/bin/activate
226
+ export AIRFLOW_HOME=$(pwd)/airflow_home
227
+ cd bq-job-optimizer-airflow-2
228
+ python test_dag_execution.py
229
+ ```
230
+ This simulates a DAG execution and verifies that:
231
+ - The plugin intercepts BigQuery jobs
232
+ - The Rabbit optimization API is called with connection credentials
233
+ - The optimized configuration is used
234
+
235
+ **Test plugin optimization (unit, no real BQ):**
236
+ ```bash
237
+ source venv/bin/activate
238
+ export AIRFLOW_HOME=$(pwd)/airflow_home
239
+ python -m unittest bq-job-optimizer-airflow-2/test_plugin_optimization.py -v
240
+ ```
241
+
242
+ 5. **Cleanup (optional):**
243
+ To remove the test environment (venv and airflow_home directories):
244
+ ```bash
245
+ ./setup_local_test.sh --clean
246
+ ```
247
+ Or use the short form:
248
+ ```bash
249
+ ./setup_local_test.sh -c
250
+ ```
251
+
252
+ ### Manual Validation Steps
253
+
254
+ 1. **Connection setup**
255
+ - Create the `rabbit_api` connection as described above.
256
+ - Verify the password is populated and (optionally) the base URL override is correct by running `airflow connections get rabbit_api`.
257
+
258
+ 2. **Variable setup**
259
+ - Set the `rabbit_bq_optimizer_config` variable using the sample JSON (without the API key).
260
+ - Include at least one reservation ID and confirm the `default_pricing_mode` is valid.
261
+
262
+ 3. **DAG validation**
263
+ - Deploy the plugin file to `$AIRFLOW_HOME/plugins`.
264
+ - Restart the scheduler/webserver/workers so the patch is applied.
265
+ - Trigger a DAG that uses `BigQueryInsertJobOperator` (or any BigQuery operator).
266
+
267
+ 4. **Positive path (connection + variable present)**
268
+ - Confirm in the scheduler logs at startup that the plugin logs `patching BigQueryHook.insert_job` and `patching BigQueryInsertJobOperator._submit_job`.
269
+ - Validate that the BigQuery job request reaches Rabbit (check Rabbit logs or enable DEBUG for `Rabbit BQ Optimizer: optimization result=...`).
270
+ - For a query with historical data/reservations, verify the resulting BigQuery job uses the optimized configuration.
271
+
272
+ 5. **Missing connection safety net**
273
+ - Temporarily rename/delete the Airflow connection and re-run the DAG.
274
+ - The scheduler logs should show `Failed to load Rabbit API connection` and the job should proceed without optimization (ensures graceful fallback).
275
+
276
+ 6. **Custom base URL regression**
277
+ - Set `api_base_url` in the connection extras to a staging endpoint (or use schema/host).
278
+ - Trigger a DAG and confirm via Rabbit logs/network traces that the request hits the custom endpoint.
279
+
280
+ 7. **Compatibility check**
281
+ - Ensure the environment installs the latest `rabbit-bq-job-optimizer` package (e.g., `pip install -U rabbit-bq-job-optimizer`).
282
+ - Run unit tests or a smoke DAG run to confirm no API contract regressions with the service.
283
+
284
+ ## Usage
285
+
286
+ The plugin works automatically with any BigQuery operator. No additional configuration is needed in your DAGs:
287
+
288
+ ```python
289
+ from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator
290
+
291
+ # The plugin will automatically optimize this job
292
+ insert_job = BigQueryInsertJobOperator(
293
+ task_id="insert_query_job",
294
+ configuration={
295
+ "query": {
296
+ "query": "SELECT * FROM `project.dataset.table`",
297
+ "useLegacySql": False
298
+ }
299
+ }
300
+ )
301
+ ```
302
+
303
+ ### Pool billing project routing
304
+
305
+ When the optimizer returns a pool billing project in
306
+ `optimizedJob.jobReference.projectId`, jobs submitted through
307
+ `BigQueryInsertJobOperator` run and poll on that project. The plugin briefly
308
+ links the operator to the hook during `_submit_job` so `operator.project_id`
309
+ and the BigQuery `jobs.insert` call use the same billing project.
310
+
311
+ Direct `BigQueryHook.insert_job` calls still receive the optimized
312
+ configuration but keep the original `project_id`. Use
313
+ `BigQueryInsertJobOperator` in DAGs when you need pool billing project
314
+ routing with deferrable tasks.
315
+
316
+ If the optimizer response has no `jobReference.projectId` (for example
317
+ reservation-only assignment), the operator keeps its configured source
318
+ `project_id`.
319
+
320
+ ### Job labels
321
+
322
+ Optimized jobs include labels you can query in BigQuery
323
+ (`INFORMATION_SCHEMA.JOBS_BY_*`) to confirm how each submit was handled:
324
+
325
+ | Label | Values | Meaning |
326
+ |-------|--------|---------|
327
+ | `rabbit-source-project` | GCP project id | Project the job was submitted from (your DAG / operator `project_id`) |
328
+ | `rabbit-pool-project` | GCP project id | Pool billing project recommended by the optimizer (present only when a pool was assigned) |
329
+ | `rabbit-pool-routing` | `applied` \| `skipped` \| `none` | `applied`: `BigQueryInsertJobOperator` submitted on `rabbit-pool-project`; `skipped`: pool recommended but submit stayed on the source project (typically a direct hook call); `none`: no pool billing project in the optimizer response |
330
+
331
+ ## Error Handling
332
+
333
+ The plugin includes comprehensive error handling for:
334
+ - Missing or invalid configuration
335
+ - Missing required fields
336
+ - Empty reservation IDs list
337
+ - API errors
338
+
339
+ In all error cases, the plugin will log a warning and proceed with the original job configuration.
340
+
341
+ ## Troubleshooting
342
+
343
+ ```
344
+ Broken plugin: `No module named 'rabbit_bq_job_optimizer'` — install `rabbit-bq-optimizer-airflow-plugin` (or `rabbit-bq-job-optimizer`) in the Airflow environment and restart.
345
+ ```
346
+
347
+ If you see this error, it means the rabbit-bq-job-optimizer package is missing from your Airflow environment. Install it by adding the package (https://pypi.org/project/rabbit-bq-job-optimizer/) to your Airflow requirements or environment.
348
+
349
+ ```
350
+ [2025-06-15, 17:25:20 UTC] {rabbit_bq_optimizer_plugin.py:82} WARNING - Rabbit BQ Optimizer: config error: 'Variable rabbit_bq_optimizer_config does not exist'. Using original job.
351
+ ```
352
+
353
+ If you see this error, it means the Airflow variable `rabbit_bq_optimizer_config` is not set or has invalid content. Make sure you have:
354
+
355
+ 1. Created the variable named exactly `rabbit_bq_optimizer_config`
356
+ 2. Set valid JSON content that includes all required fields:
357
+ ```json
358
+ {
359
+ "default_pricing_mode": "on_demand",
360
+ "reservation_ids": [
361
+ "project:us-central1.reservation-name1",
362
+ "project:us-east1.reservation-name2"
363
+ ]
364
+ }
365
+ ```
366
+ 3. Verified the JSON is properly formatted without any syntax errors
367
+
368
+ ## Development
369
+
370
+ ### Pre-commit Hooks
371
+
372
+ This repository uses pre-commit hooks to ensure code quality. To set them up:
373
+
374
+ ```bash
375
+ # Install pre-commit
376
+ pip install pre-commit
377
+
378
+ # Install the hooks
379
+ pre-commit install
380
+
381
+ # (Optional) Run hooks on all files
382
+ pre-commit run --all-files
383
+ ```
384
+
385
+ The hooks will automatically:
386
+ - **Auto-fix** formatting with Black (CI checks formatting)
387
+ - **Auto-fix** linting issues with Ruff (CI checks linting)
388
+ - Check for common issues (trailing whitespace, large files, etc.)
389
+
390
+ **Note**: Pre-commit hooks auto-fix issues for convenience, while CI runs in check-only mode to ensure nothing slips through.
391
+
392
+ ### CI/CD
393
+
394
+ GitHub Actions automatically runs on every push and pull request:
395
+ - **Linting and Formatting**: Checks code style with Black and Ruff
396
+ - **Tests**: Runs test suite on Python 3.9, 3.10, 3.11, and 3.12
397
+
398
+ ## Uninstalling
399
+
400
+ 1. Remove the plugin file from your Airflow plugins directory
401
+ 2. Restart Airflow
402
+
403
+ ## Support
404
+
405
+ For questions, API endpoint details, API key, or any issues, contact the Rabbit support team at success@followrabbit.ai
@@ -0,0 +1,16 @@
1
+ This repository contains the source code for Rabbit's Airflow plugins, specifically focusing on BigQuery job optimization. These plugins are designed to enhance Apache Airflow's capabilities when working with BigQuery, providing optimized job execution and cost saving.
2
+
3
+ ## Airflow 2 Plugin Highlights
4
+
5
+ - Patches the BigQuery hook to transparently send job configurations to the Rabbit Job Optimizer service.
6
+ - Authenticates via the official `rabbit-bq-job-optimizer` Python client (install the latest version for compatibility).
7
+ - Retrieves the Rabbit API key (and optional base URL override) from the Airflow connection `rabbit_api` so secrets stay out of plain-text variables.
8
+ - Reads optimization parameters (pricing mode, reservation IDs, etc.) from the `rabbit_bq_optimizer_config` Airflow variable.
9
+
10
+ Refer to `bq-job-optimizer-airflow-2/README.md` for installation, configuration, and the end-to-end test plan.
11
+
12
+ ## PyPI
13
+
14
+ The Airflow 2 plugin is published as [`rabbit-bq-optimizer-airflow-plugin`](https://pypi.org/project/rabbit-bq-optimizer-airflow-plugin/). Release with `./publish_to_pypi.sh` (same flow as the [python-bq-job-optimizer](https://github.com/followrabbit-ai/python-bq-job-optimizer) client).
15
+
16
+ For more information about Rabbit and our data platform, visit [https://followrabbit.ai/](https://followrabbit.ai/).