pgbee 0.1.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.
pgbee-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
pgbee-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: pgbee
3
+ Version: 0.1.0
4
+ Summary: Reference worker and installer for pgbee derived columns on PostgreSQL
5
+ Author: Simone Salerno
6
+ Author-email: Simone Salerno <doppiaesse@proton.me>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Dist: httpx2>=2.13.1
10
+ Requires-Dist: jsonschema>=4.26.0
11
+ Requires-Dist: openai>=3.19.2
12
+ Requires-Dist: psycopg[binary,pool]>=3.3.6
13
+ Requires-Dist: pydantic>=2.13.5
14
+ Requires-Dist: pydantic-settings>=2.15.0
15
+ Requires-Dist: structlog>=26.1.0
16
+ Requires-Dist: typer>=0.27.2
17
+ Requires-Python: >=3.13
18
+ Project-URL: Homepage, https://github.com/essedev/pgbee
19
+ Project-URL: Repository, https://github.com/essedev/pgbee
20
+ Project-URL: Issues, https://github.com/essedev/pgbee/issues
21
+ Project-URL: Changelog, https://github.com/essedev/pgbee/blob/main/CHANGELOG.md
22
+ Description-Content-Type: text/markdown
23
+
24
+ # pgbee
25
+
26
+ AI-derived columns for PostgreSQL. This package is the reference worker and installer:
27
+
28
+ - `pgbee install` applies the extension's SQL files to a database (works on managed Postgres too);
29
+ - `pgbee run` consumes the queue and calls the models through OpenRouter or any OpenAI-compatible endpoint (OpenAI, Azure, Ollama, vLLM), one lane per backend;
30
+ - `pgbee status` shows each derived column, its queue and its spend;
31
+ - `pgbee extension-files DIR` writes the files for `CREATE EXTENSION pgbee` on self-hosted servers.
32
+
33
+ The SQL files ship inside the package. Documentation, quickstart and source:
34
+ https://github.com/essedev/pgbee
35
+
36
+ Licensed under Apache-2.0.
pgbee-0.1.0/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # pgbee
2
+
3
+ AI-derived columns for PostgreSQL. This package is the reference worker and installer:
4
+
5
+ - `pgbee install` applies the extension's SQL files to a database (works on managed Postgres too);
6
+ - `pgbee run` consumes the queue and calls the models through OpenRouter or any OpenAI-compatible endpoint (OpenAI, Azure, Ollama, vLLM), one lane per backend;
7
+ - `pgbee status` shows each derived column, its queue and its spend;
8
+ - `pgbee extension-files DIR` writes the files for `CREATE EXTENSION pgbee` on self-hosted servers.
9
+
10
+ The SQL files ship inside the package. Documentation, quickstart and source:
11
+ https://github.com/essedev/pgbee
12
+
13
+ Licensed under Apache-2.0.
@@ -0,0 +1,77 @@
1
+ [project]
2
+ name = "pgbee"
3
+ version = "0.1.0"
4
+ description = "Reference worker and installer for pgbee derived columns on PostgreSQL"
5
+ requires-python = ">=3.13"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ readme = "README.md"
9
+ dependencies = [
10
+ "httpx2>=2.13.1",
11
+ "jsonschema>=4.26.0",
12
+ "openai>=3.19.2",
13
+ "psycopg[binary,pool]>=3.3.6",
14
+ "pydantic>=2.13.5",
15
+ "pydantic-settings>=2.15.0",
16
+ "structlog>=26.1.0",
17
+ "typer>=0.27.2",
18
+ ]
19
+
20
+ [[project.authors]]
21
+ name = "Simone Salerno"
22
+ email = "doppiaesse@proton.me"
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/essedev/pgbee"
26
+ Repository = "https://github.com/essedev/pgbee"
27
+ Issues = "https://github.com/essedev/pgbee/issues"
28
+ Changelog = "https://github.com/essedev/pgbee/blob/main/CHANGELOG.md"
29
+
30
+ [project.scripts]
31
+ pgbee = "pgbee.cli:app"
32
+
33
+ [build-system]
34
+ requires = ["uv_build>=0.10.2,<0.11.0"]
35
+ build-backend = "uv_build"
36
+
37
+ [dependency-groups]
38
+ dev = [
39
+ "mypy>=2.3.1",
40
+ "pytest>=9.1.1",
41
+ "pytest-asyncio>=1.4.0",
42
+ "ruff>=0.16.9",
43
+ "types-jsonschema>=4.26.0.20260518",
44
+ ]
45
+
46
+ [tool.ruff]
47
+ line-length = 100
48
+ target-version = "py313"
49
+
50
+ [tool.ruff.lint]
51
+ select = [
52
+ "E",
53
+ "F",
54
+ "I",
55
+ "UP",
56
+ "B",
57
+ "ASYNC",
58
+ ]
59
+
60
+ [tool.ruff.lint.per-file-ignores]
61
+ "tests/**" = ["E501"]
62
+
63
+ [tool.mypy]
64
+ strict = true
65
+ python_version = "3.13"
66
+
67
+ [[tool.mypy.overrides]]
68
+ module = ["duckdb"]
69
+ ignore_missing_imports = true
70
+
71
+ [tool.pytest.ini_options]
72
+ asyncio_mode = "auto"
73
+ markers = [
74
+ "llm: calls a real model provider, excluded by default",
75
+ "extension: needs the Postgres image with the pgbee extension (make test-extension)",
76
+ ]
77
+ addopts = "-m 'not llm and not extension'"
@@ -0,0 +1,69 @@
1
+ [project]
2
+ name = "pgbee"
3
+ version = "0.1.0"
4
+ description = "Reference worker and installer for pgbee derived columns on PostgreSQL"
5
+ authors = [
6
+ { name = "Simone Salerno", email = "doppiaesse@proton.me" }
7
+ ]
8
+ requires-python = ">=3.13"
9
+ license = "Apache-2.0"
10
+ license-files = ["LICENSE"]
11
+ readme = "README.md"
12
+ dependencies = [
13
+ "httpx2>=2.13.1",
14
+ "jsonschema>=4.26.0",
15
+ "openai>=3.19.2",
16
+ "psycopg[binary,pool]>=3.3.6",
17
+ "pydantic>=2.13.5",
18
+ "pydantic-settings>=2.15.0",
19
+ "structlog>=26.1.0",
20
+ "typer>=0.27.2",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/essedev/pgbee"
25
+ Repository = "https://github.com/essedev/pgbee"
26
+ Issues = "https://github.com/essedev/pgbee/issues"
27
+ Changelog = "https://github.com/essedev/pgbee/blob/main/CHANGELOG.md"
28
+
29
+ [project.scripts]
30
+ pgbee = "pgbee.cli:app"
31
+
32
+ [build-system]
33
+ requires = ["uv_build>=0.10.2,<0.11.0"]
34
+ build-backend = "uv_build"
35
+
36
+ [dependency-groups]
37
+ dev = [
38
+ "mypy>=2.3.1",
39
+ "pytest>=9.1.1",
40
+ "pytest-asyncio>=1.4.0",
41
+ "ruff>=0.16.9",
42
+ "types-jsonschema>=4.26.0.20260518",
43
+ ]
44
+
45
+ [tool.ruff]
46
+ line-length = 100
47
+ target-version = "py313"
48
+
49
+ [tool.ruff.lint]
50
+ select = ["E", "F", "I", "UP", "B", "ASYNC"]
51
+
52
+ [tool.ruff.lint.per-file-ignores]
53
+ "tests/**" = ["E501"]
54
+
55
+ [tool.mypy]
56
+ strict = true
57
+ python_version = "3.13"
58
+
59
+ [[tool.mypy.overrides]]
60
+ module = ["duckdb"]
61
+ ignore_missing_imports = true
62
+
63
+ [tool.pytest.ini_options]
64
+ asyncio_mode = "auto"
65
+ markers = [
66
+ "llm: calls a real model provider, excluded by default",
67
+ "extension: needs the Postgres image with the pgbee extension (make test-extension)",
68
+ ]
69
+ addopts = "-m 'not llm and not extension'"
@@ -0,0 +1 @@
1
+ """pgbee: installer and reference worker for pgbee derived columns."""
@@ -0,0 +1,231 @@
1
+ """`pgbee` command line: install the extension, run the worker, inspect derived columns."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import signal
8
+ import sys
9
+ import time
10
+ from pathlib import Path
11
+ from typing import Annotated, Any
12
+
13
+ import psycopg
14
+ import structlog
15
+ import typer
16
+ from psycopg.rows import dict_row
17
+
18
+ from pgbee import extension
19
+ from pgbee.db import WORKER_BACKENDS, Contract
20
+ from pgbee.installer import InstalledAsExtension, install
21
+ from pgbee.providers import OpenAICompatibleProvider, OpenRouterProvider, Provider
22
+ from pgbee.settings import Settings, load_settings
23
+ from pgbee.worker import Worker, WorkerPool
24
+
25
+ app = typer.Typer(no_args_is_help=True, add_completion=False)
26
+
27
+
28
+ def _configure_logging(level: str) -> None:
29
+ numeric = logging.getLevelName(level.upper())
30
+ if not isinstance(numeric, int):
31
+ numeric = logging.INFO
32
+ structlog.configure(
33
+ wrapper_class=structlog.make_filtering_bound_logger(numeric),
34
+ processors=[
35
+ structlog.processors.TimeStamper(fmt="%H:%M:%S"),
36
+ structlog.processors.add_log_level,
37
+ structlog.dev.ConsoleRenderer(colors=sys.stderr.isatty()),
38
+ ],
39
+ )
40
+
41
+
42
+ @app.command("install")
43
+ def install_cmd() -> None:
44
+ """Apply the SQL files in sql/ that the database has not seen yet."""
45
+ settings = load_settings()
46
+ with psycopg.connect(settings.database_url) as conn:
47
+ try:
48
+ applied = install(conn)
49
+ except InstalledAsExtension as exc:
50
+ raise typer.BadParameter(str(exc)) from exc
51
+ if applied:
52
+ typer.echo(f"applied: {', '.join(str(v) for v in applied)}")
53
+ else:
54
+ typer.echo("up to date")
55
+
56
+
57
+ @app.command("extension-files")
58
+ def extension_files_cmd(
59
+ out_dir: Annotated[Path, typer.Argument(help="Where to write pgbee.control and the scripts.")],
60
+ ) -> None:
61
+ """Write the files for CREATE EXTENSION pgbee, to copy into `pg_config --sharedir`/extension."""
62
+ for path in extension.build(out_dir):
63
+ typer.echo(path)
64
+
65
+
66
+ @app.command("status")
67
+ def status_cmd() -> None:
68
+ """List derived columns with their version and queue counters."""
69
+ settings = load_settings()
70
+ with psycopg.connect(settings.database_url, row_factory=dict_row) as conn:
71
+ rows = conn.execute(
72
+ "SELECT c.table_schema, c.table_name, c.column_name, c.version, c.backend, c.model,"
73
+ " c.enabled, c.pending, c.claimed, c.done, c.dead, c.stale, c.human_overrides,"
74
+ " c.backfill_pending, c.backfill_scanned,"
75
+ " b.budget_usd, b.budget_period, b.spent_usd, b.exhausted"
76
+ " FROM bee.columns c JOIN bee.budgets b ON b.column_def_id = c.id"
77
+ " ORDER BY c.table_schema, c.table_name, c.column_name"
78
+ ).fetchall()
79
+ if not rows:
80
+ typer.echo("no derived columns")
81
+ return
82
+ for r in rows:
83
+ state = "on" if r["enabled"] else "off"
84
+ typer.echo(
85
+ f"{r['table_schema']}.{r['table_name']}.{r['column_name']}"
86
+ f" v{r['version']} {r['backend']} {r['model']} [{state}]"
87
+ f" pending={r['pending']} claimed={r['claimed']} done={r['done']} dead={r['dead']}"
88
+ f" stale={r['stale']} human={r['human_overrides']}"
89
+ f"{_backfill(r)} {_spend(r)}"
90
+ )
91
+
92
+
93
+ def _backfill(r: dict[str, Any]) -> str:
94
+ if not r["backfill_pending"]:
95
+ return ""
96
+ return f" backfilling (scanned {r['backfill_scanned']} rows)"
97
+
98
+
99
+ def _spend(r: dict[str, Any]) -> str:
100
+ spent = f"${r['spent_usd']:.4f}"
101
+ if r["budget_usd"] is None:
102
+ return f"spent {spent} this {r['budget_period']}, no cap"
103
+ flag = " EXHAUSTED" if r["exhausted"] else ""
104
+ return f"spent {spent} of ${r['budget_usd']} per {r['budget_period']}{flag}"
105
+
106
+
107
+ OPENAI_DEFAULT_URL = "https://api.openai.com/v1"
108
+
109
+
110
+ def build_provider(settings: Settings) -> Provider:
111
+ try:
112
+ kind = settings.provider_kind()
113
+ except ValueError as exc:
114
+ raise typer.BadParameter(str(exc)) from exc
115
+ if kind == "openrouter":
116
+ assert settings.openrouter_api_key is not None
117
+ return OpenRouterProvider(
118
+ settings.openrouter_api_key,
119
+ settings.openrouter_base_url,
120
+ timeout=settings.request_timeout_seconds,
121
+ )
122
+ # Local servers (Ollama, vLLM) take no key, but the SDK wants a non empty one.
123
+ return OpenAICompatibleProvider(
124
+ settings.openai_api_key or "not-needed",
125
+ settings.openai_base_url or OPENAI_DEFAULT_URL,
126
+ timeout=settings.request_timeout_seconds,
127
+ )
128
+
129
+
130
+ @app.command("run")
131
+ def run_cmd(
132
+ once: bool = typer.Option(False, "--once", help="Process one batch and exit."),
133
+ drain: bool = typer.Option(
134
+ False,
135
+ "--drain",
136
+ help="Process until nothing is ready, then exit: for cron and serverless schedulers.",
137
+ ),
138
+ max_seconds: float | None = typer.Option(
139
+ None,
140
+ "--max-seconds",
141
+ min=1,
142
+ help="With --drain, stop claiming after this many seconds (the batch in flight finishes).",
143
+ ),
144
+ batch_size: int = typer.Option(20, "--batch-size", min=1),
145
+ backends: str = typer.Option(
146
+ "",
147
+ "--backends",
148
+ help="Comma separated backends this worker serves, one lane each. Default: all the"
149
+ f" provider supports ({','.join(WORKER_BACKENDS)} on OpenRouter).",
150
+ ),
151
+ ) -> None:
152
+ """Consume the queue: call the models and write the results back."""
153
+ if once and drain:
154
+ raise typer.BadParameter("--once and --drain are alternatives")
155
+ if max_seconds is not None and not drain:
156
+ raise typer.BadParameter("--max-seconds works with --drain")
157
+ settings = load_settings()
158
+ provider = build_provider(settings)
159
+ _configure_logging(settings.log_level)
160
+ chosen = [b.strip() for b in backends.split(",") if b.strip()] or list(provider.backends)
161
+ if set(chosen) - set(WORKER_BACKENDS):
162
+ raise typer.BadParameter(f"--backends takes a subset of {','.join(WORKER_BACKENDS)}")
163
+ unsupported = set(chosen) - set(provider.backends)
164
+ if unsupported:
165
+ raise typer.BadParameter(
166
+ f"{','.join(sorted(unsupported))} not available with {settings.provider_kind()}:"
167
+ " the decision backend needs OpenRouter"
168
+ )
169
+ asyncio.run(
170
+ _run(
171
+ settings,
172
+ provider,
173
+ once=once,
174
+ drain=drain,
175
+ max_seconds=max_seconds,
176
+ batch_size=batch_size,
177
+ backends=chosen,
178
+ )
179
+ )
180
+
181
+
182
+ async def _run(
183
+ settings: Settings,
184
+ provider: Provider,
185
+ *,
186
+ once: bool,
187
+ drain: bool,
188
+ max_seconds: float | None,
189
+ batch_size: int,
190
+ backends: list[str],
191
+ ) -> None:
192
+ structlog.get_logger("pgbee").info("provider", kind=settings.provider_kind(), backends=backends)
193
+ options: dict[str, Any] = {
194
+ "batch_size": batch_size,
195
+ "poll_interval": settings.poll_interval_seconds,
196
+ "claim_timeout_seconds": settings.claim_timeout_seconds,
197
+ "maintenance_interval": settings.maintenance_interval_seconds,
198
+ }
199
+ if once:
200
+ contract = await Contract.connect(settings.database_url)
201
+ try:
202
+ worker = Worker(
203
+ contract, provider, worker_id=settings.worker_id, backends=backends, **options
204
+ )
205
+ stats = await worker.run_once()
206
+ finally:
207
+ await contract.close()
208
+ typer.echo(
209
+ f"claimed={stats.claimed} failed={stats.failed} "
210
+ + " ".join(f"{k}={v}" for k, v in stats.outcomes.items())
211
+ )
212
+ return
213
+ pool = WorkerPool(
214
+ lambda: Contract.connect(settings.database_url),
215
+ provider,
216
+ worker_id=settings.worker_id,
217
+ backends=backends,
218
+ **options,
219
+ )
220
+ loop = asyncio.get_running_loop()
221
+ for sig in (signal.SIGINT, signal.SIGTERM):
222
+ loop.add_signal_handler(sig, pool.stop)
223
+ if not drain:
224
+ await pool.run_forever()
225
+ return
226
+ deadline = None if max_seconds is None else time.monotonic() + max_seconds
227
+ for backend, stats in (await pool.drain(deadline)).items():
228
+ typer.echo(
229
+ f"{backend}: claimed={stats.claimed} failed={stats.failed} "
230
+ + " ".join(f"{k}={v}" for k, v in stats.outcomes.items())
231
+ )