b3-prosaic-harness-postgres 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,222 @@
1
+ Metadata-Version: 2.4
2
+ Name: b3-prosaic-harness-postgres
3
+ Version: 0.2.1
4
+ Summary: Explicit PostgreSQL run storage for Prosaic Harness
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ License-File: NOTICE
10
+ Requires-Dist: b3-prosaic-harness<0.8,>=0.7
11
+ Requires-Dist: psycopg[binary]<4,>=3.2.3
12
+ Requires-Dist: psycopg-pool<4,>=3.2
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest>=8; extra == "test"
15
+ Requires-Dist: build>=1; extra == "test"
16
+ Requires-Dist: setuptools>=77; extra == "test"
17
+ Requires-Dist: wheel; extra == "test"
18
+ Requires-Dist: packaging; extra == "test"
19
+ Dynamic: license-file
20
+
21
+ # PostgreSQL persistence for Prosaic Harness
22
+
23
+ Run on worker A, inspect/resume on worker B, without a shared writable run
24
+ directory. Core remains database-free; install this separate adapter only when
25
+ you need shared durable state. The API is synchronous; a private I/O thread
26
+ bounds network waits. Model execution holds no database connection/transaction.
27
+ The current candidate is `b3-prosaic-harness-postgres` **0.2.0**, selecting
28
+ `b3-prosaic-harness>=0.7,<0.8`. The adapter is maintained in this repository but
29
+ installed and versioned separately, keeping PostgreSQL drivers optional for
30
+ Harness users. Imports and CLI names remain unchanged. Final qualification and
31
+ publication of the b3 release train are pending. The historical
32
+ [Harness v0.6.1 release](https://github.com/B3Cognition/prosaic-harness/releases/tag/v0.6.1)
33
+ retains its original 0.6.1/0.1.1 package names and receipts.
34
+
35
+ ## 1. Install and supply an existing database
36
+
37
+ Python 3.11+, PostgreSQL 16 or 18 on a writable primary, and libpq 17+ are
38
+ required. `psycopg[binary]` supplies libpq; older libpq is rejected.
39
+ From the exact candidate Harness checkout, use a new environment and a curated
40
+ wheelhouse containing only the manifest-selected b3 candidate wheels:
41
+
42
+ ```sh
43
+ python3 -m venv .venv-postgres
44
+ .venv-postgres/bin/python -m pip install --find-links /absolute/path/to/curated-wheelhouse . ./adapters/postgres
45
+ export PATH="$PWD/.venv-postgres/bin:$PATH"
46
+ prosaic --version
47
+ prosaic-harness-postgres --help
48
+ ```
49
+
50
+ ALWAYS migrate using a fresh environment or image; NEVER install legacy and b3
51
+ distributions together because they own the same import paths. See
52
+ [package migration](../../docs/package-migration.md). The Runtime 0.8 candidate
53
+ must be available before this installation can resolve.
54
+
55
+ Harness does **not** provision PostgreSQL, create databases/users, start a
56
+ service, or fall back to files. Your operator supplies two DSNs through a secret
57
+ manager: `HARNESS_MIGRATION_DSN` (schema owner with database CREATE permission)
58
+ and `HARNESS_RUNTIME_DSN` (restricted runtime role). Never put DSNs in Markdown,
59
+ YAML, argv, logs or Git. For a local terminal:
60
+
61
+ ```sh
62
+ export HARNESS_MIGRATION_DSN="$(python -c 'import getpass; print(getpass.getpass("Migration DSN: "))')"
63
+ export HARNESS_RUNTIME_DSN="$(python -c 'import getpass; print(getpass.getpass("Runtime DSN: "))')"
64
+ ```
65
+
66
+ Preserve operator TLS/authentication settings, e.g. `sslmode=verify-full` and
67
+ certificate roots. The adapter adds `target_session_attrs=read-write` for primary
68
+ routing; it never weakens TLS.
69
+
70
+ ## 2. Initialize once, then grant runtime access
71
+
72
+ ```sh
73
+ prosaic-harness-postgres init --dsn-env HARNESS_MIGRATION_DSN
74
+ ```
75
+
76
+ Initialization is explicit, transactional, repeatable and concurrency-safe.
77
+ It creates schema/version 1, not your database. It refuses unknown versions,
78
+ foreign-owned, partial or damaged schemas; it does not repair or downgrade them.
79
+
80
+ As schema owner, apply these grants, replacing `harness_runtime` with your
81
+ existing runtime role (role/password creation belongs to your operator):
82
+
83
+ ```sql
84
+ GRANT USAGE ON SCHEMA prosaic_harness TO harness_runtime;
85
+ GRANT SELECT ON prosaic_harness.schema_version, prosaic_harness.leases,
86
+ prosaic_harness.runs, prosaic_harness.receipts TO harness_runtime;
87
+ GRANT INSERT, UPDATE ON prosaic_harness.leases, prosaic_harness.runs TO harness_runtime;
88
+ GRANT INSERT ON prosaic_harness.receipts TO harness_runtime;
89
+ ```
90
+
91
+ Do **not** grant runtime schema CREATE, schema-version UPDATE, receipt UPDATE,
92
+ or table DELETE. Check using the actual application's credentials:
93
+
94
+ ```sh
95
+ prosaic-harness-postgres doctor --dsn-env HARNESS_RUNTIME_DSN
96
+ ```
97
+
98
+ Default doctor reads only catalogs/settings/privileges: no rows, model calls or
99
+ migrations. For an explicit write-and-cleanup test, use migration or dedicated
100
+ diagnostic credentials with DELETE on the three data tables:
101
+
102
+ ```sh
103
+ prosaic-harness-postgres doctor --dsn-env HARNESS_MIGRATION_DSN --check-write
104
+ ```
105
+
106
+ This exercises guarded create/CAS/receipt/read/release operations in a fresh
107
+ `prosaic-diagnostic-<uuid>` namespace. Reserve this prefix; applications must not
108
+ use it. Cleanup deletes only its exact receipt/run/lease identities, in that
109
+ order, after release. It never deletes production lease generations. Cleanup,
110
+ interruption and commit-ack failures fail the command. Its error includes the
111
+ diagnostic namespace for reconciliation: inspect exact rows before manual
112
+ cleanup/retry, never blindly delete by prefix.
113
+
114
+ ## 3. Embed the single Harness engine
115
+
116
+ ```python
117
+ from prosaic_harness import Harness, Workflow
118
+ from prosaic_harness_postgres import PostgresRunStore
119
+
120
+ workflow = Workflow.load('/srv/workflows/approval/pause.yml')
121
+ # Construct after fork; keep one long-lived store per bounded trusted namespace.
122
+ with PostgresRunStore.from_env('HARNESS_RUNTIME_DSN', namespace='my-app') as store:
123
+ store.check_ready() # startup gate; no implicit init
124
+ h = Harness(workflow, store=store, run_id='0123456789abcdef0123456789abcdef')
125
+ h.run({'task': 'example'}) # use a NEW UUID for each new run
126
+ snapshot = h.status() # read-only .state and opaque .revision
127
+ h.resume(choice='approve', expected_revision=snapshot.revision)
128
+ ```
129
+
130
+ Worker B reconstructs the same Workflow/namespace/run ID and calls status/resume,
131
+ not run. Human choices, structured responses and explicit interrupted-call retry
132
+ require the current revision. A stale approval cannot approve a later same-named
133
+ pause. Never silently fetch a fresh revision to bypass rejection: show current
134
+ state and require a new decision. See the [runnable example](../../examples/postgres/README.md).
135
+
136
+ `load_run` returns an independent RunSnapshot; create/save return revisions.
137
+ Receipt absence is None, corruption is an error. Writes require this store/run's
138
+ active lease. Tokens are run/namespace scoped, not lease owner/fencing tokens.
139
+ Receipts are immutable; identical repeats need live ownership. Sealed finite
140
+ JSON is limited to 8 MiB per document including UTF-8 bytes. Public APIs return
141
+ no driver objects. The legacy `Harness(workflow, run_dir)` and filesystem CLI
142
+ remain supported; the adapter adds no new workflow interpreter.
143
+
144
+ ## Deployment and safety
145
+
146
+ - All reads/writes use the authoritative writable primary, never replicas/caches.
147
+ Tables must be permanent/logged; fsync/full_page_writes must be on, effective
148
+ synchronous_commit on or remote_apply. Existing remote_apply is preserved.
149
+ Primary/WAL guards run on every operation/reconnection.
150
+ - Mount immutable workflow, prose, schema, evidence and reviewed tool assets at
151
+ identical absolute paths across workers. Keep executables, validator versions
152
+ and Runtime configuration identical. Drift fails before dispatch. PostgreSQL
153
+ moves run state, not assets or private tool scratch.
154
+ - Synchronize worker/database clocks and avoid abrupt clock steps. Expiry uses
155
+ fresh clock_timestamp() after the lease-row lock; local ownership uses a
156
+ conservative monotonic deadline starting before the request, not at reply.
157
+ - Default lease/renewal 60s/15s. Duration >=15s; renewal >=1s and <=duration/3;
158
+ renewal + operation budget + 1s must be less than duration. Default total I/O
159
+ budget 10s, pool/connect 5s, row lock 1s, statement 5s. Deadlines cover pool,
160
+ network and COMMIT waits. Stalled connections are quarantined; unresolved
161
+ operations retain capacity and prevent unsafe close.
162
+ - Default lazy pool bounds per store/process: 8 ordinary + 4 renewal connections,
163
+ maximum 4 active leases. Renewal has reserved capacity. Multiply capacity
164
+ across replicas/namespaces; do not create a pool per HTTP request. Applications
165
+ still own scheduling, model concurrency and quotas.
166
+ - Construct after fork; do not share across processes. Drain executions before
167
+ close/context exit. Threads can share a store; use a separate Harness per run.
168
+ - Namespaces are trusted isolation keys, **not authorization or DB row-level
169
+ security**. A shared DB role can directly access other namespaces. Derive
170
+ namespace/run ownership from authenticated server state, never browser/model
171
+ input. Applications own tenant authorization and admission policies.
172
+ - Raw status state contains private inputs, evidence, responses and history.
173
+ Products must expose a filtered authorized view, not the operator demo JSON.
174
+ - Prose frontmatter requests tools; Runtime/workflow permissions authorize them.
175
+ Neither grants database permissions. No HTTP service, queue, PostgreSQL server
176
+ or historical file importer is included.
177
+ - Fencing stops stale DB mutations, not external tool/model effects. Use
178
+ application-owned idempotency keys. Pending calls without receipts require
179
+ explicit fresh retry consent, not automatic redispatch. Unknown token usage
180
+ may still prevent a token-budgeted retry; abandoned calls retain their budget.
181
+ - Acknowledged WAL durability is not zero-loss asynchronous failover. A lagging
182
+ promoted primary or older backup can lose receipts/generations. Require
183
+ operator replication guarantees where needed; do not promise exactly-once
184
+ external effects from this adapter.
185
+
186
+ ## Errors and recovery
187
+
188
+ | Code | Action |
189
+ | --- | --- |
190
+ | store_uninitialized | Operator runs init, applies grants, then doctor. |
191
+ | store_incompatible | Check role/version/primary/WAL settings and intact logged schema; no automatic repair. |
192
+ | store_unavailable | Restore primary connectivity and reload status. outcome_unknown means a commit may have succeeded; never blindly repeat writes/effects. |
193
+ | run_busy | Another worker owns execution; back off without launching another call. |
194
+ | lease_lost | Stop dispatch/admission/writes, discard late output; acquire fresh execution and reconcile durable state. |
195
+ | revision_conflict | Show the user's current pause and require a new explicit decision. |
196
+ | store_busy | Drain active/queued/renewal work; construct a new store after fork. |
197
+ | receipt_conflict / store_corrupt | Stop; investigate evidence without overwriting it. |
198
+
199
+ ## Development verification
200
+
201
+ Core tests need no database/driver. Adapter tests use disposable databases and
202
+ synthetic inference, never TokenProxy. Required mode fails rather than skips
203
+ missing infrastructure. Select Podman/Docker explicitly for crash/standby gates:
204
+
205
+ ```sh
206
+ python -m pip install -e '.[test]' -e './adapters/postgres[test]'
207
+ python adapters/postgres/tests/support/local_cluster.py start --engine podman --version 16
208
+ # Retain the printed ownership.json path as FIXTURE_MANIFEST.
209
+ python adapters/postgres/tests/support/local_cluster.py test --manifest "$FIXTURE_MANIFEST"
210
+ python adapters/postgres/tests/support/local_cluster.py stop --manifest "$FIXTURE_MANIFEST"
211
+ ```
212
+
213
+ Repeat with version 18. Stop validates exact IDs/names/ownership labels before
214
+ removing only owned containers/volumes/network. Generated fixture networks and
215
+ loopback ports use synthetic trust authentication, never production defaults.
216
+ # Lease registration candidate
217
+
218
+ The adapter transfers acquisition capacity into registered
219
+ session capacity atomically under the existing store mutex. A registering lease
220
+ can no longer be counted twice while maintenance is scheduled. The database
221
+ storage/fencing contract is unchanged. A unit scheduling-boundary regression and
222
+ an owned PostgreSQL 16/18 race regression cover the transition.
@@ -0,0 +1,13 @@
1
+ b3_prosaic_harness_postgres-0.2.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
2
+ b3_prosaic_harness_postgres-0.2.1.dist-info/licenses/NOTICE,sha256=ElUIgB9aqeWDj68Un0FliVam9tItd9kKPum77UrCD8s,258
3
+ prosaic_harness_postgres/__init__.py,sha256=8v_irnkIUIB7ulxCVK5ilZ-BsxLTLzcXVe6Am5YznTM,146
4
+ prosaic_harness_postgres/cli.py,sha256=ZGjAKIRVwDEwrTKe_XZjAb4FCbge4XaoSMU91V1yB2A,4103
5
+ prosaic_harness_postgres/leases.py,sha256=Fv_yMKfpEoMBK_eR2otkpxoPN4a4JOdF_zzgTLF035E,2402
6
+ prosaic_harness_postgres/schema.py,sha256=bgA09ds5R2g6axOAhIvEmVyl4ieqDEBsRAk4l6Wt6r0,7686
7
+ prosaic_harness_postgres/store.py,sha256=nDXE8mD8RgSJzAePIHjFJg59K1xHayeLmSjasGt3Cwk,13496
8
+ prosaic_harness_postgres/transport.py,sha256=OGw4LNMq4QKys2QglzSzQf_j0zvEXlJ8PpsH_zesmq0,14178
9
+ b3_prosaic_harness_postgres-0.2.1.dist-info/METADATA,sha256=EZYesowXCIRwAONDv4baAAKezeJDAvO358R4QoWok9A,11879
10
+ b3_prosaic_harness_postgres-0.2.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
11
+ b3_prosaic_harness_postgres-0.2.1.dist-info/entry_points.txt,sha256=2j44SxhtLoMVgQnq-wmY5SVnf-LjUcm4-s2yGJmcAWY,79
12
+ b3_prosaic_harness_postgres-0.2.1.dist-info/top_level.txt,sha256=wdHvfuHjA1dMXVsvCq0tjLD76i9noP5PYs1PKHpxcWs,25
13
+ b3_prosaic_harness_postgres-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ prosaic-harness-postgres = prosaic_harness_postgres.cli:main
@@ -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.
@@ -0,0 +1,5 @@
1
+ Prosaic Harness
2
+
3
+ This project is distributed under the Apache License, Version 2.0; see LICENSE.
4
+ Third-party dependencies retain their own licenses and attribution notices.
5
+ Previously published versions and tags retain the license notices shipped with them.
@@ -0,0 +1 @@
1
+ prosaic_harness_postgres
@@ -0,0 +1,6 @@
1
+ """Separate PostgreSQL adapter for Prosaic Harness."""
2
+ __version__ = '0.2.1'
3
+
4
+ from .store import PostgresRunStore
5
+
6
+ __all__ = ['PostgresRunStore']
@@ -0,0 +1,81 @@
1
+ """Explicit operator setup; no provisioning, inference or secret arguments."""
2
+ import argparse
3
+ import json
4
+ import sys
5
+ import uuid
6
+
7
+ from prosaic_harness import StoreError, StoreIncompatible, StoreBusy
8
+ from prosaic_harness.contracts import seal
9
+ from .store import PostgresRunStore
10
+
11
+
12
+ def check_write(store):
13
+ async def permissions(conn):
14
+ for table in ('receipts', 'runs', 'leases'):
15
+ allowed = await (await conn.execute('SELECT pg_catalog.has_table_privilege(%s,%s)',
16
+ ('prosaic_harness.' + table, 'DELETE'))).fetchone()
17
+ if not allowed[0]:
18
+ raise StoreIncompatible('write diagnostic requires separate DELETE-capable credentials')
19
+ store._transport.call(permissions)
20
+ run_id, invocation_id = uuid.uuid4().hex, uuid.uuid4().hex
21
+ state = seal({'run_id': run_id, 'inputs': {'diagnostic': True}})
22
+ receipt = seal({'run_id': run_id, 'id': invocation_id, 'events': []})
23
+ async def cleanup(conn):
24
+ row = await (await conn.execute('SELECT owner FROM prosaic_harness.leases '
25
+ 'WHERE namespace=%s AND run_id=%s FOR UPDATE', (store.namespace, run_id))).fetchone()
26
+ if row and row[0] is not None:
27
+ raise StoreBusy('diagnostic cleanup incomplete; reconcile the reserved diagnostic namespace')
28
+ await conn.execute('DELETE FROM prosaic_harness.receipts WHERE namespace=%s AND run_id=%s AND invocation_id=%s',
29
+ (store.namespace, run_id, invocation_id))
30
+ await conn.execute('DELETE FROM prosaic_harness.runs WHERE namespace=%s AND run_id=%s', (store.namespace, run_id))
31
+ await conn.execute('DELETE FROM prosaic_harness.leases WHERE namespace=%s AND run_id=%s', (store.namespace, run_id))
32
+ try:
33
+ with store.lease(run_id) as lease:
34
+ first = store.create_run(run_id, state, lease)
35
+ second = store.save_run(run_id, state, first, lease)
36
+ store.save_receipt(run_id, invocation_id, receipt, lease)
37
+ if store.load_run(run_id).revision != second or store.load_receipt(run_id, invocation_id) != receipt:
38
+ raise StoreIncompatible('diagnostic persistence verification failed')
39
+ finally:
40
+ # Cleanup must acknowledge success before the command can pass.
41
+ store._transport.call(cleanup)
42
+
43
+
44
+ def main(argv=None):
45
+ parser = argparse.ArgumentParser(description='Initialize/check an existing Harness database')
46
+ commands = parser.add_subparsers(dest='command', required=True)
47
+ for name in ('init', 'doctor'):
48
+ command = commands.add_parser(name)
49
+ command.add_argument('--dsn-env', required=True, help='name of the DSN environment variable, never its value')
50
+ if name == 'doctor':
51
+ command.add_argument('--check-write', action='store_true', help='explicit disposable write test; DELETE credentials required')
52
+ args = parser.parse_args(argv)
53
+ try:
54
+ namespace = 'prosaic-diagnostic-' + uuid.uuid4().hex
55
+ with PostgresRunStore.from_env(args.dsn_env, namespace=namespace) as store:
56
+ if args.command == 'init':
57
+ store.initialize()
58
+ result = {'initialized': True, 'schema_version': 1}
59
+ else:
60
+ store.check_ready()
61
+ if args.check_write:
62
+ check_write(store)
63
+ result = {'ready': True, 'write_checked': args.check_write}
64
+ print(json.dumps(result))
65
+ return 0
66
+ except StoreError as exc:
67
+ result = {'error': exc.code, 'message': str(exc)}
68
+ if args.command == 'doctor' and args.check_write:
69
+ result['diagnostic_namespace'] = namespace
70
+ print(json.dumps(result), file=sys.stderr)
71
+ return 1
72
+ except KeyboardInterrupt:
73
+ print('{"error":"interrupted","message":"operation interrupted; reconcile before retrying"}', file=sys.stderr)
74
+ return 130
75
+ except Exception:
76
+ print('{"error":"invalid_configuration","message":"check database environment and configuration"}', file=sys.stderr)
77
+ return 1
78
+
79
+
80
+ if __name__ == '__main__':
81
+ raise SystemExit(main())
@@ -0,0 +1,64 @@
1
+ """Private renewable execution sessions; database generations fence writes."""
2
+ import asyncio
3
+ import os
4
+ import threading
5
+ import time
6
+ import uuid
7
+
8
+ from prosaic_harness import LeaseLost, StoreError, StoreBusy
9
+
10
+
11
+ class PostgresLease:
12
+ def __init__(self, store, run_id, started):
13
+ self.store, self.run_id = store, run_id
14
+ self.pid = os.getpid()
15
+ self.owner = uuid.uuid4().hex
16
+ self.generation = None
17
+ self._deadline = started + store.lease_s
18
+ self._lost = False
19
+ self._active = True
20
+ self._stopping = threading.Event()
21
+ self._stopped = threading.Event()
22
+ self._task = None
23
+ self._renewal = None
24
+
25
+ def check_valid(self):
26
+ if (self.pid != os.getpid() or not self._active or self._lost
27
+ or time.monotonic() >= self._deadline):
28
+ self._lost = True
29
+ raise LeaseLost('database execution session is no longer owned')
30
+
31
+ async def maintain(self):
32
+ self._task = asyncio.current_task()
33
+ try:
34
+ while not self._stopping.is_set():
35
+ await asyncio.sleep(self.store.renew_s)
36
+ if self._stopping.is_set():
37
+ break
38
+ started = time.monotonic()
39
+ await self.store._transport.execute_async(
40
+ lambda conn: self.store._renew(conn, self), renewal=True)
41
+ self.check_valid()
42
+ self._deadline = started + self.store.lease_s
43
+ except (StoreError, asyncio.CancelledError):
44
+ self._lost = True
45
+ except Exception:
46
+ self._lost = True
47
+ finally:
48
+ self._stopped.set()
49
+
50
+ def stop(self):
51
+ self._stopping.set()
52
+ def cancel():
53
+ if self._task is not None:
54
+ self._task.cancel()
55
+ elif self._renewal is not None:
56
+ # Submission may have raised before scheduling, or while the
57
+ # runner was still queued. Only the I/O loop can close it
58
+ # without racing its first execution.
59
+ self._renewal.close()
60
+ self._stopped.set()
61
+ self.store._transport._loop.call_soon_threadsafe(cancel)
62
+ if not self._stopped.wait(self.store._transport.operation_timeout_s + 2):
63
+ self._lost = True
64
+ raise StoreBusy('renewal task has not drained; retain store until cleanup completes')