pgque-py 0.2.0rc1__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,191 @@
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 the 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 the 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 any 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
+ Copyright 2026 Nikolay Samokhvalov
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,246 @@
1
+ Metadata-Version: 2.4
2
+ Name: pgque-py
3
+ Version: 0.2.0rc1
4
+ Summary: Python client for PgQue -- PgQ Universal Edition
5
+ Author-email: Nikolay Samokhvalov <nik@postgres.ai>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/NikolayS/pgque
8
+ Project-URL: Repository, https://github.com/NikolayS/pgque
9
+ Project-URL: Issues, https://github.com/NikolayS/pgque/issues
10
+ Project-URL: Documentation, https://github.com/NikolayS/pgque/blob/main/docs/reference.md
11
+ Keywords: postgres,postgresql,queue,pgq,pgque,background-jobs
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Topic :: Database
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: psycopg[binary]<4,>=3.1
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.0; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # pgque-py
32
+
33
+ Python client for [PgQue](https://github.com/NikolayS/pgque) — the PgQ-based
34
+ universal PostgreSQL queue. Thin wrapper over `pgque-api` SQL functions:
35
+ `send`, `receive`, `ack`, `nack`, `force_next_tick`, plus a polling
36
+ `Consumer` with `LISTEN`/`NOTIFY` wakeup.
37
+
38
+ ## Install
39
+
40
+ After the first Python client release:
41
+
42
+ ```bash
43
+ pip install pgque-py
44
+ ```
45
+
46
+ Requires Python 3.10+ and PostgreSQL 14+ with the PgQue schema installed
47
+ (`\i pgque.sql` — no extension required).
48
+
49
+ ## Database permissions
50
+
51
+ The connecting database role needs `pgque_reader` to consume (`receive`, `ack`, `nack`, `subscribe`, `unsubscribe`) and `pgque_writer` to produce (`send`, `send_batch`). The two are **siblings** — neither inherits the other. An app that both produces and consumes (the typical case for code using this client) must be granted **both** roles:
52
+
53
+ ```sql
54
+ grant pgque_reader to your_app_user;
55
+ grant pgque_writer to your_app_user;
56
+ ```
57
+
58
+ See [`docs/reference.md` — Roles and grants](../../docs/reference.md#roles-and-grants) for the full role table.
59
+
60
+ ## Quickstart
61
+
62
+ ```python
63
+ import pgque
64
+
65
+ with pgque.connect("postgresql://localhost/mydb") as client:
66
+ # one-time setup (typically in a migration)
67
+ client.conn.execute("select pgque.subscribe('orders', 'order_worker')")
68
+ client.conn.commit()
69
+
70
+ # producer: commit once to publish both calls atomically
71
+ event_id = client.send("orders", {"order_id": 42}, type="order.created")
72
+ batch_ids = client.send_batch("orders", "order.created", [
73
+ {"order_id": 43},
74
+ {"order_id": 44},
75
+ ])
76
+ client.conn.commit()
77
+ print(event_id, batch_ids)
78
+
79
+ # consumer (separate process / thread)
80
+ consumer = pgque.Consumer(
81
+ dsn="postgresql://localhost/mydb",
82
+ queue="orders",
83
+ name="order_worker",
84
+ )
85
+
86
+ @consumer.on("order.created")
87
+ def handle_order(msg: pgque.Message) -> None:
88
+ print(f"got {msg.type}: {msg.payload}")
89
+
90
+ # Optional: catch-all handler for types with no specific handler.
91
+ # Without it, messages with unhandled types are nacked by default
92
+ # (sent to retry_queue, or to the dead-letter queue once
93
+ # queue_max_retries is exhausted). Register a "*" handler to take
94
+ # explicit control.
95
+ @consumer.on("*")
96
+ def handle_unknown(msg: pgque.Message) -> None:
97
+ print(f"unhandled type {msg.type!r}: {msg.payload}")
98
+
99
+ consumer.start() # blocks until SIGTERM / SIGINT
100
+ ```
101
+
102
+ ### Consumer options
103
+
104
+ `Consumer(..., max_messages=...)` controls the per-`receive` limit.
105
+ The default is PostgreSQL's `int` maximum, so the consumer requests
106
+ the whole PgQ batch before acknowledging it. `ack()` finishes the
107
+ entire underlying PgQ batch, including rows beyond `max_messages`;
108
+ only lower this value when it is at least as large as the queue's
109
+ worst-case batch size, otherwise rows past the limit are silently
110
+ skipped by the batch ack.
111
+
112
+ ### Handling unknown event types
113
+
114
+ By default the consumer **nacks** any message whose type has no
115
+ registered handler and no `"*"` catch-all. The message is retried (or
116
+ dead-lettered once `queue_max_retries` is exhausted) so unknown types
117
+ are never silently dropped.
118
+
119
+ To ack unknown types instead, pass `unknown_handler_policy="ack"`:
120
+
121
+ ```python
122
+ consumer = pgque.Consumer(
123
+ dsn="postgresql://localhost/mydb",
124
+ queue="orders",
125
+ name="order_worker",
126
+ unknown_handler_policy="ack", # log WARNING and ack; do not nack
127
+ )
128
+ ```
129
+
130
+ ## Experimental: cooperative consumers
131
+
132
+ > **Experimental in PgQue 0.2.** Function names, edge-case behavior, and
133
+ > client API shape may change before this feature is marked stable. Do
134
+ > not use this as the only processing path for critical workloads
135
+ > without idempotent handlers and stale-worker takeover tests.
136
+
137
+ Cooperative consumers let several worker processes share **one logical
138
+ consumer**. Each batch is handed to exactly one subconsumer; the main
139
+ row owns the group cursor, member rows own active batches. See
140
+ [`docs/reference.md` — Cooperative consumers / subconsumers](../../docs/reference.md#cooperative-consumers--subconsumers)
141
+ for the SQL surface.
142
+
143
+ Two-worker example (each worker holds its own connection / process):
144
+
145
+ ```python
146
+ import pgque
147
+
148
+ # worker-1
149
+ c1 = pgque.Consumer(
150
+ dsn="postgresql://localhost/mydb",
151
+ queue="orders",
152
+ name="order_worker",
153
+ subconsumer="worker-1",
154
+ dead_interval="5 minutes", # optional: take over a stale sibling
155
+ )
156
+
157
+ @c1.on("order.created")
158
+ def handle(msg):
159
+ process(msg)
160
+
161
+ c1.start() # in a second process: subconsumer="worker-2"
162
+ ```
163
+
164
+ `Consumer(subconsumer=...)` switches the poll loop to
165
+ `receive_coop` and auto-registers the `coop_main` + `coop_member` rows
166
+ on the first call. `dead_interval` is only valid in cooperative mode;
167
+ passing it without `subconsumer` raises `ValueError`.
168
+
169
+ The low-level methods on `PgqueClient` are also available for direct
170
+ use:
171
+
172
+ ```python
173
+ client.subscribe_subconsumer("orders", "order_worker", "worker-1")
174
+ msgs = client.receive_coop(
175
+ "orders", "order_worker", "worker-1",
176
+ max_messages=100, dead_interval="5 minutes",
177
+ )
178
+ client.ack(msgs[0].batch_id)
179
+ client.touch_subconsumer("orders", "order_worker", "worker-1")
180
+ client.unsubscribe_subconsumer(
181
+ "orders", "order_worker", "worker-1", batch_handling=1,
182
+ )
183
+ ```
184
+
185
+ `unsubscribe_subconsumer(..., batch_handling=0)` (the default) raises if
186
+ the subconsumer holds an active batch; pass `batch_handling=1` to route
187
+ active messages through retry/DLQ before removal.
188
+
189
+ A runnable two-worker demo lives at
190
+ [`bench/coop_demo.py`](bench/coop_demo.py); run it against any pgque
191
+ database with `PGQUE_TEST_DSN` set.
192
+
193
+ ## Manual ticking
194
+
195
+ For tests, demos, or manual operation without `pg_cron`, use
196
+ `client.force_next_tick(queue)` to force the **next** `pgque.ticker()` call to
197
+ materialize a tick. It does not insert the tick itself:
198
+
199
+ ```python
200
+ client.force_next_tick("orders")
201
+ client.conn.execute("select pgque.ticker()")
202
+ client.conn.commit()
203
+ ```
204
+
205
+ `client.force_tick(queue)` remains as a deprecated compatibility alias.
206
+
207
+ ## Transactions
208
+
209
+ `send` → ticker → `receive` must each run in its own committed transaction (PgQue is snapshot-based). `pgque.connect(dsn)` is non-autocommit by default — commit between produce and consumer. The `Consumer` is autocommit + explicit `conn.transaction()` around `receive + dispatch + ack`.
210
+
211
+ Don't wrap `send` and `receive` in one explicit tx; same for `maint_retry_events` + `ticker`. See [snapshot rule](https://github.com/NikolayS/pgque/blob/main/docs/pgq-concepts.md#snapshot-rule).
212
+
213
+
214
+ ## Tests
215
+
216
+ Integration tests require a running PostgreSQL with the PgQue schema
217
+ installed. Set `PGQUE_TEST_DSN` and run pytest:
218
+
219
+ ```bash
220
+ PGQUE_TEST_DSN=postgresql://postgres:pgque_test@localhost/pgque_test \
221
+ pytest clients/python/tests
222
+ ```
223
+
224
+ Without `PGQUE_TEST_DSN`, the tests skip.
225
+
226
+ ## Distribution
227
+
228
+ The PyPI distribution is `pgque-py`; the import package is `pgque`:
229
+
230
+ ```python
231
+ import pgque
232
+ ```
233
+
234
+ See [RELEASE.md](RELEASE.md) for publishing steps.
235
+
236
+ ## More
237
+
238
+ - Schema install, full reference, tutorial:
239
+ <https://github.com/NikolayS/pgque>
240
+ - Per-function SQL reference:
241
+ <https://github.com/NikolayS/pgque/blob/main/docs/reference.md>
242
+ - Issues: <https://github.com/NikolayS/pgque/issues>
243
+
244
+ ## License
245
+
246
+ Apache-2.0. Copyright 2026 Nikolay Samokhvalov.
@@ -0,0 +1,216 @@
1
+ # pgque-py
2
+
3
+ Python client for [PgQue](https://github.com/NikolayS/pgque) — the PgQ-based
4
+ universal PostgreSQL queue. Thin wrapper over `pgque-api` SQL functions:
5
+ `send`, `receive`, `ack`, `nack`, `force_next_tick`, plus a polling
6
+ `Consumer` with `LISTEN`/`NOTIFY` wakeup.
7
+
8
+ ## Install
9
+
10
+ After the first Python client release:
11
+
12
+ ```bash
13
+ pip install pgque-py
14
+ ```
15
+
16
+ Requires Python 3.10+ and PostgreSQL 14+ with the PgQue schema installed
17
+ (`\i pgque.sql` — no extension required).
18
+
19
+ ## Database permissions
20
+
21
+ The connecting database role needs `pgque_reader` to consume (`receive`, `ack`, `nack`, `subscribe`, `unsubscribe`) and `pgque_writer` to produce (`send`, `send_batch`). The two are **siblings** — neither inherits the other. An app that both produces and consumes (the typical case for code using this client) must be granted **both** roles:
22
+
23
+ ```sql
24
+ grant pgque_reader to your_app_user;
25
+ grant pgque_writer to your_app_user;
26
+ ```
27
+
28
+ See [`docs/reference.md` — Roles and grants](../../docs/reference.md#roles-and-grants) for the full role table.
29
+
30
+ ## Quickstart
31
+
32
+ ```python
33
+ import pgque
34
+
35
+ with pgque.connect("postgresql://localhost/mydb") as client:
36
+ # one-time setup (typically in a migration)
37
+ client.conn.execute("select pgque.subscribe('orders', 'order_worker')")
38
+ client.conn.commit()
39
+
40
+ # producer: commit once to publish both calls atomically
41
+ event_id = client.send("orders", {"order_id": 42}, type="order.created")
42
+ batch_ids = client.send_batch("orders", "order.created", [
43
+ {"order_id": 43},
44
+ {"order_id": 44},
45
+ ])
46
+ client.conn.commit()
47
+ print(event_id, batch_ids)
48
+
49
+ # consumer (separate process / thread)
50
+ consumer = pgque.Consumer(
51
+ dsn="postgresql://localhost/mydb",
52
+ queue="orders",
53
+ name="order_worker",
54
+ )
55
+
56
+ @consumer.on("order.created")
57
+ def handle_order(msg: pgque.Message) -> None:
58
+ print(f"got {msg.type}: {msg.payload}")
59
+
60
+ # Optional: catch-all handler for types with no specific handler.
61
+ # Without it, messages with unhandled types are nacked by default
62
+ # (sent to retry_queue, or to the dead-letter queue once
63
+ # queue_max_retries is exhausted). Register a "*" handler to take
64
+ # explicit control.
65
+ @consumer.on("*")
66
+ def handle_unknown(msg: pgque.Message) -> None:
67
+ print(f"unhandled type {msg.type!r}: {msg.payload}")
68
+
69
+ consumer.start() # blocks until SIGTERM / SIGINT
70
+ ```
71
+
72
+ ### Consumer options
73
+
74
+ `Consumer(..., max_messages=...)` controls the per-`receive` limit.
75
+ The default is PostgreSQL's `int` maximum, so the consumer requests
76
+ the whole PgQ batch before acknowledging it. `ack()` finishes the
77
+ entire underlying PgQ batch, including rows beyond `max_messages`;
78
+ only lower this value when it is at least as large as the queue's
79
+ worst-case batch size, otherwise rows past the limit are silently
80
+ skipped by the batch ack.
81
+
82
+ ### Handling unknown event types
83
+
84
+ By default the consumer **nacks** any message whose type has no
85
+ registered handler and no `"*"` catch-all. The message is retried (or
86
+ dead-lettered once `queue_max_retries` is exhausted) so unknown types
87
+ are never silently dropped.
88
+
89
+ To ack unknown types instead, pass `unknown_handler_policy="ack"`:
90
+
91
+ ```python
92
+ consumer = pgque.Consumer(
93
+ dsn="postgresql://localhost/mydb",
94
+ queue="orders",
95
+ name="order_worker",
96
+ unknown_handler_policy="ack", # log WARNING and ack; do not nack
97
+ )
98
+ ```
99
+
100
+ ## Experimental: cooperative consumers
101
+
102
+ > **Experimental in PgQue 0.2.** Function names, edge-case behavior, and
103
+ > client API shape may change before this feature is marked stable. Do
104
+ > not use this as the only processing path for critical workloads
105
+ > without idempotent handlers and stale-worker takeover tests.
106
+
107
+ Cooperative consumers let several worker processes share **one logical
108
+ consumer**. Each batch is handed to exactly one subconsumer; the main
109
+ row owns the group cursor, member rows own active batches. See
110
+ [`docs/reference.md` — Cooperative consumers / subconsumers](../../docs/reference.md#cooperative-consumers--subconsumers)
111
+ for the SQL surface.
112
+
113
+ Two-worker example (each worker holds its own connection / process):
114
+
115
+ ```python
116
+ import pgque
117
+
118
+ # worker-1
119
+ c1 = pgque.Consumer(
120
+ dsn="postgresql://localhost/mydb",
121
+ queue="orders",
122
+ name="order_worker",
123
+ subconsumer="worker-1",
124
+ dead_interval="5 minutes", # optional: take over a stale sibling
125
+ )
126
+
127
+ @c1.on("order.created")
128
+ def handle(msg):
129
+ process(msg)
130
+
131
+ c1.start() # in a second process: subconsumer="worker-2"
132
+ ```
133
+
134
+ `Consumer(subconsumer=...)` switches the poll loop to
135
+ `receive_coop` and auto-registers the `coop_main` + `coop_member` rows
136
+ on the first call. `dead_interval` is only valid in cooperative mode;
137
+ passing it without `subconsumer` raises `ValueError`.
138
+
139
+ The low-level methods on `PgqueClient` are also available for direct
140
+ use:
141
+
142
+ ```python
143
+ client.subscribe_subconsumer("orders", "order_worker", "worker-1")
144
+ msgs = client.receive_coop(
145
+ "orders", "order_worker", "worker-1",
146
+ max_messages=100, dead_interval="5 minutes",
147
+ )
148
+ client.ack(msgs[0].batch_id)
149
+ client.touch_subconsumer("orders", "order_worker", "worker-1")
150
+ client.unsubscribe_subconsumer(
151
+ "orders", "order_worker", "worker-1", batch_handling=1,
152
+ )
153
+ ```
154
+
155
+ `unsubscribe_subconsumer(..., batch_handling=0)` (the default) raises if
156
+ the subconsumer holds an active batch; pass `batch_handling=1` to route
157
+ active messages through retry/DLQ before removal.
158
+
159
+ A runnable two-worker demo lives at
160
+ [`bench/coop_demo.py`](bench/coop_demo.py); run it against any pgque
161
+ database with `PGQUE_TEST_DSN` set.
162
+
163
+ ## Manual ticking
164
+
165
+ For tests, demos, or manual operation without `pg_cron`, use
166
+ `client.force_next_tick(queue)` to force the **next** `pgque.ticker()` call to
167
+ materialize a tick. It does not insert the tick itself:
168
+
169
+ ```python
170
+ client.force_next_tick("orders")
171
+ client.conn.execute("select pgque.ticker()")
172
+ client.conn.commit()
173
+ ```
174
+
175
+ `client.force_tick(queue)` remains as a deprecated compatibility alias.
176
+
177
+ ## Transactions
178
+
179
+ `send` → ticker → `receive` must each run in its own committed transaction (PgQue is snapshot-based). `pgque.connect(dsn)` is non-autocommit by default — commit between produce and consumer. The `Consumer` is autocommit + explicit `conn.transaction()` around `receive + dispatch + ack`.
180
+
181
+ Don't wrap `send` and `receive` in one explicit tx; same for `maint_retry_events` + `ticker`. See [snapshot rule](https://github.com/NikolayS/pgque/blob/main/docs/pgq-concepts.md#snapshot-rule).
182
+
183
+
184
+ ## Tests
185
+
186
+ Integration tests require a running PostgreSQL with the PgQue schema
187
+ installed. Set `PGQUE_TEST_DSN` and run pytest:
188
+
189
+ ```bash
190
+ PGQUE_TEST_DSN=postgresql://postgres:pgque_test@localhost/pgque_test \
191
+ pytest clients/python/tests
192
+ ```
193
+
194
+ Without `PGQUE_TEST_DSN`, the tests skip.
195
+
196
+ ## Distribution
197
+
198
+ The PyPI distribution is `pgque-py`; the import package is `pgque`:
199
+
200
+ ```python
201
+ import pgque
202
+ ```
203
+
204
+ See [RELEASE.md](RELEASE.md) for publishing steps.
205
+
206
+ ## More
207
+
208
+ - Schema install, full reference, tutorial:
209
+ <https://github.com/NikolayS/pgque>
210
+ - Per-function SQL reference:
211
+ <https://github.com/NikolayS/pgque/blob/main/docs/reference.md>
212
+ - Issues: <https://github.com/NikolayS/pgque/issues>
213
+
214
+ ## License
215
+
216
+ Apache-2.0. Copyright 2026 Nikolay Samokhvalov.