credit-ledger 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.
@@ -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 2026 Isaac Teague Frayling
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,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: credit-ledger
3
+ Version: 0.1.0
4
+ Summary: Atomic, overdraft-proof, idempotent credit metering over Postgres. Extracted from PANTHEON.
5
+ Author: Isaac Teague Frayling
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://pantheonlabs.info
8
+ Keywords: metering,billing,credits,idempotency,postgres,multi-tenant,row-level-security
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: SQLAlchemy>=2.0
13
+ Provides-Extra: postgres
14
+ Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest>=7; extra == "test"
17
+ Dynamic: license-file
18
+
19
+ # credit-ledger
20
+
21
+ [![tests](https://github.com/Igfray/pantheon-credit-ledger/actions/workflows/ci.yml/badge.svg)](https://github.com/Igfray/pantheon-credit-ledger/actions/workflows/ci.yml)
22
+ [![PyPI](https://img.shields.io/pypi/v/credit-ledger.svg)](https://pypi.org/project/credit-ledger/)
23
+ [![Python](https://img.shields.io/pypi/pyversions/credit-ledger.svg)](https://pypi.org/project/credit-ledger/)
24
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
25
+
26
+ **An atomic, overdraft-proof, idempotent credit ledger — for metering money on a pay-per-use or multi-tenant service.** ~150 lines of Python over Postgres. Extracted from [PANTHEON](https://pantheonlabs.info), a multi-tenant AI substrate, where it's the money path for autonomous AI agents that spend real credits on every turn.
27
+
28
+ The interesting part isn't the size — it's that three properties that are usually gotten *subtly wrong* are each guaranteed by a single, boring database mechanism instead of application-level hope:
29
+
30
+ | Property | How | Not by |
31
+ |---|---|---|
32
+ | **No overdraft, ever** — a balance can never go negative, even under a stampede of concurrent charges | one guarded `UPDATE … WHERE credits >= n` | `SELECT` then `UPDATE` (a race), or a mutex (doesn't survive multiple processes) |
33
+ | **Exactly-once under retries** — a replayed charge (a Stripe webhook fired twice, a client retry) charges once | `UNIQUE(tenant_id, idempotency_key)` on an append-only ledger | de-duping in app code (another race) |
34
+ | **Tenant isolation** — tenant A can't read or write tenant B's balance | Postgres row-level security, `FORCE`d | a `WHERE tenant_id = ?` you have to remember to add every time |
35
+
36
+ ## The core: one statement does the hard part
37
+
38
+ A spend is a single guarded, atomic `UPDATE`:
39
+
40
+ ```sql
41
+ UPDATE credit_balance
42
+ SET credits = credits - :n
43
+ WHERE tenant_id = :t AND credits >= :n
44
+ RETURNING credits;
45
+ ```
46
+
47
+ - The row lock **serialises** concurrent charges against the same tenant — no lost updates.
48
+ - The `credits >= :n` guard makes overdraft **structurally impossible**: the charge either fully succeeds (a row comes back) or changes nothing (zero rows). There is no window between the check and the debit, because they're the same statement.
49
+
50
+ That's the whole trick, and the test proves it: fire **100 concurrent spends of 1 credit against a balance of 50**, and *exactly 50* succeed — the balance lands at 0, never negative, with 50 ledger rows.
51
+
52
+ ```python
53
+ # tests/test_metering.py
54
+ def test_atomic_decrement_under_concurrency(engine, tenant):
55
+ metering.grant(tenant, 50, engine=engine)
56
+ with ThreadPoolExecutor(max_workers=20) as ex:
57
+ results = list(ex.map(lambda _: metering.decrement(tenant, 1, engine=pool).ok, range(100)))
58
+ assert sum(results) == 50 # exactly the balance, no more
59
+ assert metering.balance(tenant, engine=engine) == 0.0 # never negative
60
+ ```
61
+
62
+ ## Idempotency: the ledger *is* the dedup
63
+
64
+ Every grant and spend appends a row to `credit_ledger`, which carries a `UNIQUE(tenant_id, idempotency_key)`. Pass an `idempotency_key` (a Stripe `event_id`, a request id) and a replay can't insert a second row — the database rejects it, and the code returns the *original* result marked `deduped=True`. Money is never double-counted, and a duplicate never surfaces as a 500.
65
+
66
+ The subtle bit is the concurrent race: two identical charges arrive at once, both past the "already seen?" check, both try to insert. One wins; the other's `INSERT` violates the constraint, which **rolls back its whole transaction — including the decrement**. The loser then re-reads the ledger, finds the winner's row, and returns that. So a concurrent duplicate is a clean dedup, not a double-charge and not an error. There's a test for exactly this — 20 concurrent replays of one Stripe event → *one* credit applied, zero exceptions.
67
+
68
+ ## The correctness detail most people miss: fail loud, not phantom-success
69
+
70
+ An `IntegrityError` after retries is ambiguous — it could be a genuine concurrent dedup (the winner committed, there's a ledger row), **or** it could be a foreign-key violation because the tenant doesn't exist (nothing landed). Reporting success in the second case would silently lose money. So the code disambiguates by re-reading the ledger: a row means real dedup → report success; no row means nothing happened → **fail loud** (`ok=False`). This came out of an adversarial self-audit of the substrate; it's the difference between "looks fine" and "correct."
71
+
72
+ ## The RLS footgun this quietly avoids
73
+
74
+ Row-level security is only a guarantee if the writer is actually subject to it. Metering runs on a *privileged* app role (the money path is infrastructure), and on any managed Postgres that role is **not** `BYPASSRLS`. So before every transaction the code binds the tenant into a session variable the policy reads:
75
+
76
+ ```python
77
+ c.execute(text("SELECT set_config('app.current_tenant', :t, true)"), {"t": tenant_id})
78
+ ```
79
+
80
+ Skip this and, the moment RLS is enforced in production, the guarded `UPDATE` matches zero rows and the `INSERT`'s `WITH CHECK` fails — **billing silently bricks**, while every dev box (superuser, RLS bypassed) looks perfectly fine. Getting this right is the difference between a demo and something you'd run.
81
+
82
+ ## Why so little code
83
+
84
+ The database does the concurrency, the atomicity, and the isolation. The code's entire job is to *use those primitives correctly* — bind the tenant, guard the decrement, key the ledger, and disambiguate the one genuinely-ambiguous failure. Fewer moving parts is the point, not an accident.
85
+
86
+ ## Use it
87
+
88
+ ```bash
89
+ pip install -e . # SQLAlchemy is the only runtime dep
90
+ createdb ledger && psql "$DATABASE_URL" -f schema.sql
91
+ ```
92
+
93
+ ```python
94
+ from credit_ledger import metering
95
+
96
+ metering.grant(tenant_id, 100, idempotency_key="stripe:evt:abc") # top up (Stripe-retry-safe)
97
+ c = metering.decrement(tenant_id, 1, reason="chat-turn") # spend
98
+ if not c.ok:
99
+ ... # out of credits — nothing was charged
100
+ metering.balance(tenant_id) # -> float
101
+ ```
102
+
103
+ Every function also takes an explicit `engine=` (for your own pool/lifecycle). `schema.sql` is the full Postgres schema including the RLS policies.
104
+
105
+ ## Run the tests
106
+
107
+ ```bash
108
+ DATABASE_URL=postgresql://localhost/ledger pytest -q # needs Postgres + schema.sql applied
109
+ ```
110
+
111
+ The suite is the spec: overdraft impossibility under 100-way concurrency, idempotent spend and grant retries, concurrent Stripe-replay dedup, and rejection of non-positive grants (a negative "grant" would decrement a tenant — the primitive refuses it before touching the DB).
112
+
113
+ ## Design notes
114
+
115
+ A few deliberate choices, and the answers to the sharp questions they invite:
116
+
117
+ - **A failed (insufficient) charge records nothing — so a retry with the same key re-attempts. That's intended.** Idempotency dedups *successful effects*, not attempts. A charge rejected for insufficient balance didn't happen, so the same key should be free to succeed later — e.g. a metered webhook that hit a zero balance and is retried after a top-up. The dedup keys the *committed ledger row*, which only exists for charges that actually landed.
118
+ - **`numeric(18,4)` in the database, `float` at the API boundary.** The stored balance and every ledger delta are exact decimals — no binary-float drift on the money itself. The functions return `float` for ergonomics, which is fine for integer-ish credits; if you were metering *actual currency*, return `Decimal` at the boundary too (a one-line change) so nothing rounds on the way out.
119
+ - **Why two attempts is enough** (`for _attempt in range(2)`). Under N concurrent charges sharing one key, exactly one wins the `UNIQUE(tenant_id, idempotency_key)` insert and commits; every loser's `INSERT` raises, rolling back its whole transaction (decrement included). On the second pass the losers see the winner's now-committed ledger row in the "already seen?" read and return *that* — a clean dedup. A third attempt can't be needed: once the winner commits, the row is visible, so attempt two is always either the winner's own success or a loser's dedup. The re-read *after* the loop only exists to distinguish the genuinely-nothing-landed case (e.g. a foreign-key violation) — so a constraint error is never reported as phantom success.
120
+
121
+ ## Context
122
+
123
+ This is one self-contained piece of **[PANTHEON](https://pantheonlabs.info)** — a multi-tenant substrate for running AI agents safely on other people's money and data (tenancy + RLS isolation, a governed reasoning loop, an approval queue, this metering ledger, and a quality gate), designed and built solo. The live Studio at [pantheonlabs.info](https://pantheonlabs.info) runs on it; the flagship write-up is at [pantheonlabs.co.uk](https://pantheonlabs.co.uk). Built by Isaac Teague Frayling.
124
+
125
+ ## License
126
+
127
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,109 @@
1
+ # credit-ledger
2
+
3
+ [![tests](https://github.com/Igfray/pantheon-credit-ledger/actions/workflows/ci.yml/badge.svg)](https://github.com/Igfray/pantheon-credit-ledger/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/credit-ledger.svg)](https://pypi.org/project/credit-ledger/)
5
+ [![Python](https://img.shields.io/pypi/pyversions/credit-ledger.svg)](https://pypi.org/project/credit-ledger/)
6
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
7
+
8
+ **An atomic, overdraft-proof, idempotent credit ledger — for metering money on a pay-per-use or multi-tenant service.** ~150 lines of Python over Postgres. Extracted from [PANTHEON](https://pantheonlabs.info), a multi-tenant AI substrate, where it's the money path for autonomous AI agents that spend real credits on every turn.
9
+
10
+ The interesting part isn't the size — it's that three properties that are usually gotten *subtly wrong* are each guaranteed by a single, boring database mechanism instead of application-level hope:
11
+
12
+ | Property | How | Not by |
13
+ |---|---|---|
14
+ | **No overdraft, ever** — a balance can never go negative, even under a stampede of concurrent charges | one guarded `UPDATE … WHERE credits >= n` | `SELECT` then `UPDATE` (a race), or a mutex (doesn't survive multiple processes) |
15
+ | **Exactly-once under retries** — a replayed charge (a Stripe webhook fired twice, a client retry) charges once | `UNIQUE(tenant_id, idempotency_key)` on an append-only ledger | de-duping in app code (another race) |
16
+ | **Tenant isolation** — tenant A can't read or write tenant B's balance | Postgres row-level security, `FORCE`d | a `WHERE tenant_id = ?` you have to remember to add every time |
17
+
18
+ ## The core: one statement does the hard part
19
+
20
+ A spend is a single guarded, atomic `UPDATE`:
21
+
22
+ ```sql
23
+ UPDATE credit_balance
24
+ SET credits = credits - :n
25
+ WHERE tenant_id = :t AND credits >= :n
26
+ RETURNING credits;
27
+ ```
28
+
29
+ - The row lock **serialises** concurrent charges against the same tenant — no lost updates.
30
+ - The `credits >= :n` guard makes overdraft **structurally impossible**: the charge either fully succeeds (a row comes back) or changes nothing (zero rows). There is no window between the check and the debit, because they're the same statement.
31
+
32
+ That's the whole trick, and the test proves it: fire **100 concurrent spends of 1 credit against a balance of 50**, and *exactly 50* succeed — the balance lands at 0, never negative, with 50 ledger rows.
33
+
34
+ ```python
35
+ # tests/test_metering.py
36
+ def test_atomic_decrement_under_concurrency(engine, tenant):
37
+ metering.grant(tenant, 50, engine=engine)
38
+ with ThreadPoolExecutor(max_workers=20) as ex:
39
+ results = list(ex.map(lambda _: metering.decrement(tenant, 1, engine=pool).ok, range(100)))
40
+ assert sum(results) == 50 # exactly the balance, no more
41
+ assert metering.balance(tenant, engine=engine) == 0.0 # never negative
42
+ ```
43
+
44
+ ## Idempotency: the ledger *is* the dedup
45
+
46
+ Every grant and spend appends a row to `credit_ledger`, which carries a `UNIQUE(tenant_id, idempotency_key)`. Pass an `idempotency_key` (a Stripe `event_id`, a request id) and a replay can't insert a second row — the database rejects it, and the code returns the *original* result marked `deduped=True`. Money is never double-counted, and a duplicate never surfaces as a 500.
47
+
48
+ The subtle bit is the concurrent race: two identical charges arrive at once, both past the "already seen?" check, both try to insert. One wins; the other's `INSERT` violates the constraint, which **rolls back its whole transaction — including the decrement**. The loser then re-reads the ledger, finds the winner's row, and returns that. So a concurrent duplicate is a clean dedup, not a double-charge and not an error. There's a test for exactly this — 20 concurrent replays of one Stripe event → *one* credit applied, zero exceptions.
49
+
50
+ ## The correctness detail most people miss: fail loud, not phantom-success
51
+
52
+ An `IntegrityError` after retries is ambiguous — it could be a genuine concurrent dedup (the winner committed, there's a ledger row), **or** it could be a foreign-key violation because the tenant doesn't exist (nothing landed). Reporting success in the second case would silently lose money. So the code disambiguates by re-reading the ledger: a row means real dedup → report success; no row means nothing happened → **fail loud** (`ok=False`). This came out of an adversarial self-audit of the substrate; it's the difference between "looks fine" and "correct."
53
+
54
+ ## The RLS footgun this quietly avoids
55
+
56
+ Row-level security is only a guarantee if the writer is actually subject to it. Metering runs on a *privileged* app role (the money path is infrastructure), and on any managed Postgres that role is **not** `BYPASSRLS`. So before every transaction the code binds the tenant into a session variable the policy reads:
57
+
58
+ ```python
59
+ c.execute(text("SELECT set_config('app.current_tenant', :t, true)"), {"t": tenant_id})
60
+ ```
61
+
62
+ Skip this and, the moment RLS is enforced in production, the guarded `UPDATE` matches zero rows and the `INSERT`'s `WITH CHECK` fails — **billing silently bricks**, while every dev box (superuser, RLS bypassed) looks perfectly fine. Getting this right is the difference between a demo and something you'd run.
63
+
64
+ ## Why so little code
65
+
66
+ The database does the concurrency, the atomicity, and the isolation. The code's entire job is to *use those primitives correctly* — bind the tenant, guard the decrement, key the ledger, and disambiguate the one genuinely-ambiguous failure. Fewer moving parts is the point, not an accident.
67
+
68
+ ## Use it
69
+
70
+ ```bash
71
+ pip install -e . # SQLAlchemy is the only runtime dep
72
+ createdb ledger && psql "$DATABASE_URL" -f schema.sql
73
+ ```
74
+
75
+ ```python
76
+ from credit_ledger import metering
77
+
78
+ metering.grant(tenant_id, 100, idempotency_key="stripe:evt:abc") # top up (Stripe-retry-safe)
79
+ c = metering.decrement(tenant_id, 1, reason="chat-turn") # spend
80
+ if not c.ok:
81
+ ... # out of credits — nothing was charged
82
+ metering.balance(tenant_id) # -> float
83
+ ```
84
+
85
+ Every function also takes an explicit `engine=` (for your own pool/lifecycle). `schema.sql` is the full Postgres schema including the RLS policies.
86
+
87
+ ## Run the tests
88
+
89
+ ```bash
90
+ DATABASE_URL=postgresql://localhost/ledger pytest -q # needs Postgres + schema.sql applied
91
+ ```
92
+
93
+ The suite is the spec: overdraft impossibility under 100-way concurrency, idempotent spend and grant retries, concurrent Stripe-replay dedup, and rejection of non-positive grants (a negative "grant" would decrement a tenant — the primitive refuses it before touching the DB).
94
+
95
+ ## Design notes
96
+
97
+ A few deliberate choices, and the answers to the sharp questions they invite:
98
+
99
+ - **A failed (insufficient) charge records nothing — so a retry with the same key re-attempts. That's intended.** Idempotency dedups *successful effects*, not attempts. A charge rejected for insufficient balance didn't happen, so the same key should be free to succeed later — e.g. a metered webhook that hit a zero balance and is retried after a top-up. The dedup keys the *committed ledger row*, which only exists for charges that actually landed.
100
+ - **`numeric(18,4)` in the database, `float` at the API boundary.** The stored balance and every ledger delta are exact decimals — no binary-float drift on the money itself. The functions return `float` for ergonomics, which is fine for integer-ish credits; if you were metering *actual currency*, return `Decimal` at the boundary too (a one-line change) so nothing rounds on the way out.
101
+ - **Why two attempts is enough** (`for _attempt in range(2)`). Under N concurrent charges sharing one key, exactly one wins the `UNIQUE(tenant_id, idempotency_key)` insert and commits; every loser's `INSERT` raises, rolling back its whole transaction (decrement included). On the second pass the losers see the winner's now-committed ledger row in the "already seen?" read and return *that* — a clean dedup. A third attempt can't be needed: once the winner commits, the row is visible, so attempt two is always either the winner's own success or a loser's dedup. The re-read *after* the loop only exists to distinguish the genuinely-nothing-landed case (e.g. a foreign-key violation) — so a constraint error is never reported as phantom success.
102
+
103
+ ## Context
104
+
105
+ This is one self-contained piece of **[PANTHEON](https://pantheonlabs.info)** — a multi-tenant substrate for running AI agents safely on other people's money and data (tenancy + RLS isolation, a governed reasoning loop, an approval queue, this metering ledger, and a quality gate), designed and built solo. The live Studio at [pantheonlabs.info](https://pantheonlabs.info) runs on it; the flagship write-up is at [pantheonlabs.co.uk](https://pantheonlabs.co.uk). Built by Isaac Teague Frayling.
106
+
107
+ ## License
108
+
109
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,6 @@
1
+ # Copyright 2026 Isaac Teague Frayling
2
+ # Licensed under the Apache License, Version 2.0 (see LICENSE).
3
+ """credit-ledger — atomic, overdraft-proof, idempotent credit metering over Postgres."""
4
+ from .metering import Charge, balance, configure, decrement, grant
5
+
6
+ __all__ = ["Charge", "balance", "configure", "decrement", "grant"]
@@ -0,0 +1,169 @@
1
+ # Copyright 2026 Isaac Teague Frayling
2
+ # Licensed under the Apache License, Version 2.0 (see LICENSE).
3
+ """Atomic, overdraft-proof, idempotent credit metering.
4
+
5
+ The whole charge is one guarded UPDATE:
6
+
7
+ UPDATE credit_balance SET credits = credits - n WHERE tenant_id = :t AND credits >= n
8
+
9
+ The row lock serialises concurrent charges; the ``credits >= n`` guard makes overdraft
10
+ impossible — a charge either fully succeeds or doesn't happen. Every charge is written
11
+ to an append-only ledger; ``UNIQUE(tenant_id, idempotency_key)`` makes a retried charge a
12
+ no-op (and, on a concurrent dup, the loser's transaction rolls back its decrement too).
13
+
14
+ Runs on a PRIVILEGED database role (the money path is infrastructure) and scopes by
15
+ ``tenant_id`` explicitly; row-level security on the tables is defence-in-depth — hence the
16
+ per-transaction bind of the ``app.current_tenant`` GUC so those privileged writes still
17
+ satisfy the tenant-isolation policy on any Postgres where the role is not BYPASSRLS.
18
+
19
+ Extracted from PANTHEON (a multi-tenant AI substrate). See README.md for the design notes.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import logging
24
+ import os
25
+ import uuid
26
+ from dataclasses import dataclass
27
+
28
+ from sqlalchemy import create_engine, text
29
+ from sqlalchemy.exc import IntegrityError
30
+
31
+ log = logging.getLogger("credit_ledger.metering")
32
+
33
+ # The Postgres GUC (session/txn variable) that carries the current tenant for row-level security.
34
+ # Set per-transaction by _bind so writes on a non-BYPASSRLS role satisfy the tenant_isolation policy.
35
+ # Override via the env var if your schema uses a different GUC name.
36
+ TENANT_GUC = os.environ.get("CREDIT_LEDGER_TENANT_GUC", "app.current_tenant")
37
+
38
+ _ENGINE = None
39
+ _DATABASE_URL = os.environ.get("DATABASE_URL")
40
+
41
+
42
+ def configure(database_url: str) -> None:
43
+ """Set the default database URL (alternative to the ``DATABASE_URL`` env var). Optional: every
44
+ public function also accepts an explicit ``engine=`` for full control over pooling / lifecycle."""
45
+ global _DATABASE_URL, _ENGINE
46
+ _DATABASE_URL = database_url
47
+ _ENGINE = None
48
+
49
+
50
+ def _engine():
51
+ global _ENGINE
52
+ if _ENGINE is None:
53
+ if not _DATABASE_URL:
54
+ raise RuntimeError(
55
+ "No database configured — set DATABASE_URL, call configure(url), or pass engine=.")
56
+ _ENGINE = create_engine(_DATABASE_URL, future=True)
57
+ return _ENGINE
58
+
59
+
60
+ def _bind(c, tenant_id: str) -> None:
61
+ """Bind the RLS tenant GUC for this transaction so a privileged engine's writes satisfy the
62
+ tenant_isolation policy on any Postgres where the role is NOT BYPASSRLS (every managed offering,
63
+ and a hardened self-host). Harmless on a superuser dev box. Without it, the decrement matches
64
+ zero rows and the INSERT's WITH CHECK fails the moment RLS is actually enforced — billing
65
+ silently bricks in prod."""
66
+ c.execute(text("SELECT set_config(:g, :t, true)"), {"g": TENANT_GUC, "t": str(tenant_id)})
67
+
68
+
69
+ @dataclass
70
+ class Charge:
71
+ ok: bool
72
+ balance: float
73
+ deduped: bool = False
74
+
75
+
76
+ def balance(tenant_id: str, *, engine=None) -> float:
77
+ eng = engine or _engine()
78
+ with eng.begin() as c:
79
+ _bind(c, tenant_id)
80
+ v = c.execute(text("SELECT credits FROM credit_balance WHERE tenant_id = :t"),
81
+ {"t": str(tenant_id)}).scalar()
82
+ return float(v) if v is not None else 0.0
83
+
84
+
85
+ def grant(tenant_id: str, amount: float, *, reason: str = "grant",
86
+ idempotency_key: str | None = None, engine=None) -> Charge:
87
+ """Add credits. Idempotent on ``idempotency_key`` (e.g. a Stripe ``event_id``): a retried or
88
+ concurrently-replayed grant is a no-op, not a double-credit or a 500. The ledger's
89
+ ``UNIQUE(tenant_id, idempotency_key)`` is the real guarantee; the retry loop turns a racing
90
+ duplicate (which would otherwise surface an IntegrityError) into a clean dedup."""
91
+ if not amount > 0: # invariant at the primitive: a non-positive grant would
92
+ raise ValueError(f"grant amount must be positive, got {amount!r}") # decrement/brick a tenant.
93
+ eng = engine or _engine()
94
+ for _attempt in range(2):
95
+ try:
96
+ with eng.begin() as c:
97
+ _bind(c, tenant_id)
98
+ if idempotency_key:
99
+ prior = c.execute(text("SELECT balance_after FROM credit_ledger "
100
+ "WHERE tenant_id=:t AND idempotency_key=:k"),
101
+ {"t": str(tenant_id), "k": idempotency_key}).scalar()
102
+ if prior is not None:
103
+ return Charge(ok=True, balance=float(prior), deduped=True)
104
+ bal = c.execute(text(
105
+ "INSERT INTO credit_balance (tenant_id, credits) VALUES (:t, :a) "
106
+ "ON CONFLICT (tenant_id) DO UPDATE SET credits = credit_balance.credits + :a, "
107
+ "updated_at = now() RETURNING credits"),
108
+ {"t": str(tenant_id), "a": amount}).scalar()
109
+ c.execute(text("INSERT INTO credit_ledger (id, tenant_id, delta, reason, idempotency_key, balance_after) "
110
+ "VALUES (:id,:t,:d,:r,:k,:b)"),
111
+ {"id": str(uuid.uuid4()), "t": str(tenant_id), "d": amount,
112
+ "r": reason, "k": idempotency_key, "b": bal})
113
+ return Charge(ok=True, balance=float(bal))
114
+ except IntegrityError: # a constraint blocked it — could be a concurrent
115
+ continue # same-key dedup OR an FK (no such tenant); decide below
116
+ # Both attempts hit a constraint. If a ledger row exists for this key, it was a genuine concurrent
117
+ # dedup (the winner committed). If NOT, nothing landed (e.g. an FK violation: the tenant doesn't
118
+ # exist) — fail LOUD rather than report a phantom success that silently loses money.
119
+ prior = None
120
+ if idempotency_key:
121
+ with eng.begin() as c:
122
+ _bind(c, tenant_id)
123
+ prior = c.execute(text("SELECT balance_after FROM credit_ledger "
124
+ "WHERE tenant_id=:t AND idempotency_key=:k"),
125
+ {"t": str(tenant_id), "k": idempotency_key}).scalar()
126
+ if prior is not None:
127
+ return Charge(ok=True, balance=float(prior), deduped=True)
128
+ log.error("grant did NOT land for tenant %s (key=%r) — no ledger row after retries (no such tenant?)",
129
+ tenant_id, idempotency_key)
130
+ return Charge(ok=False, balance=balance(tenant_id, engine=eng))
131
+
132
+
133
+ def decrement(tenant_id: str, amount: float = 1.0, *, reason: str = "usage",
134
+ idempotency_key: str | None = None, engine=None) -> Charge:
135
+ """Atomically spend `amount` credits. Returns ok=False (no change) if insufficient."""
136
+ eng = engine or _engine()
137
+ for _attempt in range(2):
138
+ try:
139
+ with eng.begin() as c:
140
+ _bind(c, tenant_id)
141
+ if idempotency_key:
142
+ prior = c.execute(text("SELECT balance_after FROM credit_ledger "
143
+ "WHERE tenant_id=:t AND idempotency_key=:k"),
144
+ {"t": str(tenant_id), "k": idempotency_key}).scalar()
145
+ if prior is not None:
146
+ return Charge(ok=True, balance=float(prior), deduped=True)
147
+ bal = c.execute(text(
148
+ "UPDATE credit_balance SET credits = credits - :n, updated_at = now() "
149
+ "WHERE tenant_id = :t AND credits >= :n RETURNING credits"),
150
+ {"t": str(tenant_id), "n": amount}).scalar()
151
+ if bal is None: # insufficient — no change
152
+ cur = c.execute(text("SELECT credits FROM credit_balance WHERE tenant_id=:t"),
153
+ {"t": str(tenant_id)}).scalar()
154
+ return Charge(ok=False, balance=float(cur) if cur is not None else 0.0)
155
+ c.execute(text("INSERT INTO credit_ledger (id, tenant_id, delta, reason, idempotency_key, balance_after) "
156
+ "VALUES (:id,:t,:d,:r,:k,:b)"),
157
+ {"id": str(uuid.uuid4()), "t": str(tenant_id), "d": -amount,
158
+ "r": reason, "k": idempotency_key, "b": bal})
159
+ return Charge(ok=True, balance=float(bal))
160
+ except IntegrityError: # concurrent same idempotency_key
161
+ continue # txn rolled back (incl. decrement); retry → dedup
162
+ with eng.begin() as c:
163
+ _bind(c, tenant_id)
164
+ prior = c.execute(text("SELECT balance_after FROM credit_ledger "
165
+ "WHERE tenant_id=:t AND idempotency_key=:k"),
166
+ {"t": str(tenant_id), "k": idempotency_key}).scalar()
167
+ if prior is None: # IntegrityError but NO prior row → not a real dedup;
168
+ return Charge(ok=False, balance=balance(tenant_id, engine=eng)) # don't report a phantom success
169
+ return Charge(ok=True, balance=float(prior), deduped=True)
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: credit-ledger
3
+ Version: 0.1.0
4
+ Summary: Atomic, overdraft-proof, idempotent credit metering over Postgres. Extracted from PANTHEON.
5
+ Author: Isaac Teague Frayling
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://pantheonlabs.info
8
+ Keywords: metering,billing,credits,idempotency,postgres,multi-tenant,row-level-security
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: SQLAlchemy>=2.0
13
+ Provides-Extra: postgres
14
+ Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest>=7; extra == "test"
17
+ Dynamic: license-file
18
+
19
+ # credit-ledger
20
+
21
+ [![tests](https://github.com/Igfray/pantheon-credit-ledger/actions/workflows/ci.yml/badge.svg)](https://github.com/Igfray/pantheon-credit-ledger/actions/workflows/ci.yml)
22
+ [![PyPI](https://img.shields.io/pypi/v/credit-ledger.svg)](https://pypi.org/project/credit-ledger/)
23
+ [![Python](https://img.shields.io/pypi/pyversions/credit-ledger.svg)](https://pypi.org/project/credit-ledger/)
24
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
25
+
26
+ **An atomic, overdraft-proof, idempotent credit ledger — for metering money on a pay-per-use or multi-tenant service.** ~150 lines of Python over Postgres. Extracted from [PANTHEON](https://pantheonlabs.info), a multi-tenant AI substrate, where it's the money path for autonomous AI agents that spend real credits on every turn.
27
+
28
+ The interesting part isn't the size — it's that three properties that are usually gotten *subtly wrong* are each guaranteed by a single, boring database mechanism instead of application-level hope:
29
+
30
+ | Property | How | Not by |
31
+ |---|---|---|
32
+ | **No overdraft, ever** — a balance can never go negative, even under a stampede of concurrent charges | one guarded `UPDATE … WHERE credits >= n` | `SELECT` then `UPDATE` (a race), or a mutex (doesn't survive multiple processes) |
33
+ | **Exactly-once under retries** — a replayed charge (a Stripe webhook fired twice, a client retry) charges once | `UNIQUE(tenant_id, idempotency_key)` on an append-only ledger | de-duping in app code (another race) |
34
+ | **Tenant isolation** — tenant A can't read or write tenant B's balance | Postgres row-level security, `FORCE`d | a `WHERE tenant_id = ?` you have to remember to add every time |
35
+
36
+ ## The core: one statement does the hard part
37
+
38
+ A spend is a single guarded, atomic `UPDATE`:
39
+
40
+ ```sql
41
+ UPDATE credit_balance
42
+ SET credits = credits - :n
43
+ WHERE tenant_id = :t AND credits >= :n
44
+ RETURNING credits;
45
+ ```
46
+
47
+ - The row lock **serialises** concurrent charges against the same tenant — no lost updates.
48
+ - The `credits >= :n` guard makes overdraft **structurally impossible**: the charge either fully succeeds (a row comes back) or changes nothing (zero rows). There is no window between the check and the debit, because they're the same statement.
49
+
50
+ That's the whole trick, and the test proves it: fire **100 concurrent spends of 1 credit against a balance of 50**, and *exactly 50* succeed — the balance lands at 0, never negative, with 50 ledger rows.
51
+
52
+ ```python
53
+ # tests/test_metering.py
54
+ def test_atomic_decrement_under_concurrency(engine, tenant):
55
+ metering.grant(tenant, 50, engine=engine)
56
+ with ThreadPoolExecutor(max_workers=20) as ex:
57
+ results = list(ex.map(lambda _: metering.decrement(tenant, 1, engine=pool).ok, range(100)))
58
+ assert sum(results) == 50 # exactly the balance, no more
59
+ assert metering.balance(tenant, engine=engine) == 0.0 # never negative
60
+ ```
61
+
62
+ ## Idempotency: the ledger *is* the dedup
63
+
64
+ Every grant and spend appends a row to `credit_ledger`, which carries a `UNIQUE(tenant_id, idempotency_key)`. Pass an `idempotency_key` (a Stripe `event_id`, a request id) and a replay can't insert a second row — the database rejects it, and the code returns the *original* result marked `deduped=True`. Money is never double-counted, and a duplicate never surfaces as a 500.
65
+
66
+ The subtle bit is the concurrent race: two identical charges arrive at once, both past the "already seen?" check, both try to insert. One wins; the other's `INSERT` violates the constraint, which **rolls back its whole transaction — including the decrement**. The loser then re-reads the ledger, finds the winner's row, and returns that. So a concurrent duplicate is a clean dedup, not a double-charge and not an error. There's a test for exactly this — 20 concurrent replays of one Stripe event → *one* credit applied, zero exceptions.
67
+
68
+ ## The correctness detail most people miss: fail loud, not phantom-success
69
+
70
+ An `IntegrityError` after retries is ambiguous — it could be a genuine concurrent dedup (the winner committed, there's a ledger row), **or** it could be a foreign-key violation because the tenant doesn't exist (nothing landed). Reporting success in the second case would silently lose money. So the code disambiguates by re-reading the ledger: a row means real dedup → report success; no row means nothing happened → **fail loud** (`ok=False`). This came out of an adversarial self-audit of the substrate; it's the difference between "looks fine" and "correct."
71
+
72
+ ## The RLS footgun this quietly avoids
73
+
74
+ Row-level security is only a guarantee if the writer is actually subject to it. Metering runs on a *privileged* app role (the money path is infrastructure), and on any managed Postgres that role is **not** `BYPASSRLS`. So before every transaction the code binds the tenant into a session variable the policy reads:
75
+
76
+ ```python
77
+ c.execute(text("SELECT set_config('app.current_tenant', :t, true)"), {"t": tenant_id})
78
+ ```
79
+
80
+ Skip this and, the moment RLS is enforced in production, the guarded `UPDATE` matches zero rows and the `INSERT`'s `WITH CHECK` fails — **billing silently bricks**, while every dev box (superuser, RLS bypassed) looks perfectly fine. Getting this right is the difference between a demo and something you'd run.
81
+
82
+ ## Why so little code
83
+
84
+ The database does the concurrency, the atomicity, and the isolation. The code's entire job is to *use those primitives correctly* — bind the tenant, guard the decrement, key the ledger, and disambiguate the one genuinely-ambiguous failure. Fewer moving parts is the point, not an accident.
85
+
86
+ ## Use it
87
+
88
+ ```bash
89
+ pip install -e . # SQLAlchemy is the only runtime dep
90
+ createdb ledger && psql "$DATABASE_URL" -f schema.sql
91
+ ```
92
+
93
+ ```python
94
+ from credit_ledger import metering
95
+
96
+ metering.grant(tenant_id, 100, idempotency_key="stripe:evt:abc") # top up (Stripe-retry-safe)
97
+ c = metering.decrement(tenant_id, 1, reason="chat-turn") # spend
98
+ if not c.ok:
99
+ ... # out of credits — nothing was charged
100
+ metering.balance(tenant_id) # -> float
101
+ ```
102
+
103
+ Every function also takes an explicit `engine=` (for your own pool/lifecycle). `schema.sql` is the full Postgres schema including the RLS policies.
104
+
105
+ ## Run the tests
106
+
107
+ ```bash
108
+ DATABASE_URL=postgresql://localhost/ledger pytest -q # needs Postgres + schema.sql applied
109
+ ```
110
+
111
+ The suite is the spec: overdraft impossibility under 100-way concurrency, idempotent spend and grant retries, concurrent Stripe-replay dedup, and rejection of non-positive grants (a negative "grant" would decrement a tenant — the primitive refuses it before touching the DB).
112
+
113
+ ## Design notes
114
+
115
+ A few deliberate choices, and the answers to the sharp questions they invite:
116
+
117
+ - **A failed (insufficient) charge records nothing — so a retry with the same key re-attempts. That's intended.** Idempotency dedups *successful effects*, not attempts. A charge rejected for insufficient balance didn't happen, so the same key should be free to succeed later — e.g. a metered webhook that hit a zero balance and is retried after a top-up. The dedup keys the *committed ledger row*, which only exists for charges that actually landed.
118
+ - **`numeric(18,4)` in the database, `float` at the API boundary.** The stored balance and every ledger delta are exact decimals — no binary-float drift on the money itself. The functions return `float` for ergonomics, which is fine for integer-ish credits; if you were metering *actual currency*, return `Decimal` at the boundary too (a one-line change) so nothing rounds on the way out.
119
+ - **Why two attempts is enough** (`for _attempt in range(2)`). Under N concurrent charges sharing one key, exactly one wins the `UNIQUE(tenant_id, idempotency_key)` insert and commits; every loser's `INSERT` raises, rolling back its whole transaction (decrement included). On the second pass the losers see the winner's now-committed ledger row in the "already seen?" read and return *that* — a clean dedup. A third attempt can't be needed: once the winner commits, the row is visible, so attempt two is always either the winner's own success or a loser's dedup. The re-read *after* the loop only exists to distinguish the genuinely-nothing-landed case (e.g. a foreign-key violation) — so a constraint error is never reported as phantom success.
120
+
121
+ ## Context
122
+
123
+ This is one self-contained piece of **[PANTHEON](https://pantheonlabs.info)** — a multi-tenant substrate for running AI agents safely on other people's money and data (tenancy + RLS isolation, a governed reasoning loop, an approval queue, this metering ledger, and a quality gate), designed and built solo. The live Studio at [pantheonlabs.info](https://pantheonlabs.info) runs on it; the flagship write-up is at [pantheonlabs.co.uk](https://pantheonlabs.co.uk). Built by Isaac Teague Frayling.
124
+
125
+ ## License
126
+
127
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ credit_ledger/__init__.py
5
+ credit_ledger/metering.py
6
+ credit_ledger.egg-info/PKG-INFO
7
+ credit_ledger.egg-info/SOURCES.txt
8
+ credit_ledger.egg-info/dependency_links.txt
9
+ credit_ledger.egg-info/requires.txt
10
+ credit_ledger.egg-info/top_level.txt
11
+ tests/test_metering.py
@@ -0,0 +1,7 @@
1
+ SQLAlchemy>=2.0
2
+
3
+ [postgres]
4
+ psycopg[binary]>=3.1
5
+
6
+ [test]
7
+ pytest>=7
@@ -0,0 +1 @@
1
+ credit_ledger
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "credit-ledger"
3
+ version = "0.1.0"
4
+ description = "Atomic, overdraft-proof, idempotent credit metering over Postgres. Extracted from PANTHEON."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = { text = "Apache-2.0" }
8
+ authors = [{ name = "Isaac Teague Frayling" }]
9
+ keywords = ["metering", "billing", "credits", "idempotency", "postgres", "multi-tenant", "row-level-security"]
10
+ dependencies = ["SQLAlchemy>=2.0"]
11
+
12
+ [project.optional-dependencies]
13
+ postgres = ["psycopg[binary]>=3.1"]
14
+ test = ["pytest>=7"]
15
+
16
+ [project.urls]
17
+ Homepage = "https://pantheonlabs.info"
18
+
19
+ [build-system]
20
+ requires = ["setuptools>=68"]
21
+ build-backend = "setuptools.build_meta"
22
+
23
+ [tool.setuptools]
24
+ packages = ["credit_ledger"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,125 @@
1
+ # Copyright 2026 Isaac Teague Frayling
2
+ # Licensed under the Apache License, Version 2.0 (see LICENSE).
3
+ """Atomic credit metering — no overdraft under concurrency, idempotent retries.
4
+
5
+ Needs a Postgres reachable at $DATABASE_URL with schema.sql applied:
6
+ createdb ledger_test
7
+ psql "$DATABASE_URL" -f schema.sql
8
+ DATABASE_URL=postgresql://localhost/ledger_test pytest -q
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import uuid
14
+ from concurrent.futures import ThreadPoolExecutor
15
+
16
+ import pytest
17
+ from sqlalchemy import create_engine, text
18
+
19
+ from credit_ledger import metering
20
+
21
+ DB_URL = os.environ.get("DATABASE_URL")
22
+
23
+
24
+ @pytest.fixture(scope="module")
25
+ def engine():
26
+ if not DB_URL:
27
+ pytest.skip("set DATABASE_URL to a Postgres with schema.sql applied")
28
+ eng = create_engine(DB_URL, future=True)
29
+ try:
30
+ with eng.connect() as c:
31
+ c.execute(text("SELECT 1 FROM credit_balance LIMIT 0")) # schema applied?
32
+ except Exception as exc: # noqa: BLE001
33
+ pytest.skip(f"apply schema.sql first: {exc}")
34
+ return eng
35
+
36
+
37
+ @pytest.fixture()
38
+ def tenant(engine):
39
+ tid = uuid.uuid4()
40
+ with engine.begin() as c:
41
+ c.execute(text("INSERT INTO tenants (id, slug, name) VALUES (:id,:s,:n)"),
42
+ {"id": str(tid), "s": f"t-{tid.hex[:8]}", "n": f"t-{tid.hex[:8]}"})
43
+ yield str(tid)
44
+ with engine.begin() as c:
45
+ c.execute(text("DELETE FROM tenants WHERE id=:id"), {"id": str(tid)}) # cascades
46
+
47
+
48
+ def test_grant_and_spend(engine, tenant):
49
+ assert metering.grant(tenant, 10, engine=engine).balance == 10.0
50
+ r = metering.decrement(tenant, 3, engine=engine)
51
+ assert r.ok and r.balance == 7.0
52
+ assert metering.balance(tenant, engine=engine) == 7.0
53
+
54
+
55
+ def test_insufficient_is_rejected_without_change(engine, tenant):
56
+ metering.grant(tenant, 2, engine=engine)
57
+ r = metering.decrement(tenant, 5, engine=engine)
58
+ assert r.ok is False and r.balance == 2.0 # unchanged
59
+ assert metering.balance(tenant, engine=engine) == 2.0
60
+
61
+
62
+ def test_idempotent_retry_charges_once(engine, tenant):
63
+ metering.grant(tenant, 10, engine=engine)
64
+ a = metering.decrement(tenant, 4, idempotency_key="charge-1", engine=engine)
65
+ b = metering.decrement(tenant, 4, idempotency_key="charge-1", engine=engine) # retry
66
+ assert a.ok and b.ok and b.deduped is True
67
+ assert metering.balance(tenant, engine=engine) == 6.0 # charged once, not twice
68
+
69
+
70
+ def test_grant_idempotent_retry_credits_once(engine, tenant):
71
+ a = metering.grant(tenant, 100, idempotency_key="stripe:evt:abc", engine=engine)
72
+ b = metering.grant(tenant, 100, idempotency_key="stripe:evt:abc", engine=engine) # Stripe retry
73
+ assert a.ok and b.ok and b.deduped is True
74
+ assert metering.balance(tenant, engine=engine) == 100.0 # credited once, not 200
75
+
76
+
77
+ # ── ★ atomic under concurrency: no overdraft, no double-spend ─────────────────
78
+ def test_atomic_decrement_under_concurrency(engine, tenant):
79
+ metering.grant(tenant, 50, engine=engine)
80
+ # 100 concurrent spends of 1 against a balance of 50 → exactly 50 succeed
81
+ pool_engine = create_engine(DB_URL, future=True, pool_size=20, max_overflow=20)
82
+
83
+ def spend(_i):
84
+ return metering.decrement(tenant, 1, reason="race", engine=pool_engine).ok
85
+
86
+ with ThreadPoolExecutor(max_workers=20) as ex:
87
+ results = list(ex.map(spend, range(100)))
88
+
89
+ pool_engine.dispose()
90
+ assert sum(results) == 50 # exactly the balance, no more
91
+ assert metering.balance(tenant, engine=engine) == 0.0 # never negative
92
+ with engine.begin() as c:
93
+ spent = c.execute(text("SELECT count(*) FROM credit_ledger "
94
+ "WHERE tenant_id=:t AND reason='race'"), {"t": tenant}).scalar()
95
+ assert spent == 50 # one ledger row per successful spend
96
+
97
+
98
+ # ── ★ grant is retry-safe under concurrency: a replayed Stripe event credits once ─
99
+ def test_grant_idempotent_under_concurrency(engine, tenant):
100
+ # 20 concurrent grants of the SAME event_id → exactly one credit, and none raises / 500s
101
+ pool_engine = create_engine(DB_URL, future=True, pool_size=20, max_overflow=20)
102
+
103
+ def give(_i):
104
+ return metering.grant(tenant, 100, reason="stripe", idempotency_key="stripe:evt:race",
105
+ engine=pool_engine)
106
+
107
+ with ThreadPoolExecutor(max_workers=20) as ex:
108
+ results = list(ex.map(give, range(20)))
109
+
110
+ pool_engine.dispose()
111
+ assert all(r.ok for r in results) # every call returned a clean Charge, no 500
112
+ assert metering.balance(tenant, engine=engine) == 100.0 # exactly one grant applied, not 20
113
+ with engine.begin() as c:
114
+ rows = c.execute(text("SELECT count(*) FROM credit_ledger "
115
+ "WHERE tenant_id=:t AND idempotency_key='stripe:evt:race'"),
116
+ {"t": tenant}).scalar()
117
+ assert rows == 1 # one ledger row, not 20
118
+
119
+
120
+ @pytest.mark.parametrize("bad", [0, -1, -100.0])
121
+ def test_grant_rejects_non_positive_amounts(bad):
122
+ # A non-positive grant would DECREMENT (brick) a tenant or 500; the primitive must refuse it loudly,
123
+ # before touching the DB — so the invariant lives at the money primitive, not only in each caller.
124
+ with pytest.raises(ValueError):
125
+ metering.grant("00000000-0000-0000-0000-000000000000", bad, reason="bad", engine="UNUSED")