pin-derive 0.4.1__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,28 @@
1
+ node_modules/
2
+ .playwright-mcp/
3
+ *.log
4
+ .DS_Store
5
+
6
+ # Local agent/orchestration tooling state
7
+ .omc/
8
+ .claude/
9
+
10
+ # Local-only docs (proprietary / internal design notes)
11
+ docs.local/
12
+
13
+ # Local agent tool artifacts (gonk/pie RLM cache + run logs, memory db)
14
+ .gonk/
15
+ memory/
16
+ .agents/
17
+ traces/
18
+
19
+ # Generated package build output
20
+ /dist/
21
+
22
+ # Cargo build artifacts
23
+ rust/target/
24
+ __pycache__/
25
+
26
+ # moon
27
+ .moon/cache
28
+ .moon/docker
@@ -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 David Robinson
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,106 @@
1
+ Metadata-Version: 2.5
2
+ Name: pin-derive
3
+ Version: 0.4.1
4
+ Summary: Python bindings for the pin-derive bidirectional constraint engine
5
+ Project-URL: Repository, https://github.com/nightwork-dev/pin-derive
6
+ Project-URL: Issues, https://github.com/nightwork-dev/pin-derive/issues
7
+ Project-URL: Documentation, https://nightwork-dev.github.io/pin-derive/
8
+ Author: Nightwork
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: constraints,procedural-generation,solver,wasm,wasmtime
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: wasmtime>=27
23
+ Provides-Extra: dev
24
+ Requires-Dist: build>=1.2; extra == 'dev'
25
+ Requires-Dist: mypy>=1.13; extra == 'dev'
26
+ Requires-Dist: pytest>=8; extra == 'dev'
27
+ Requires-Dist: twine>=5; extra == 'dev'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # pin-derive for Python
31
+
32
+ Python bindings for **pin-derive**, a small bidirectional constraint engine: declare
33
+ cells and multidirectional relations, pin any subset, and the rest derive from the
34
+ same network.
35
+
36
+ The TypeScript engine in the repository root is the reference implementation. This
37
+ package runs the Rust/wasm core through the `wasmtime` Python runtime and is held to
38
+ the same conformance fixtures.
39
+
40
+ ## Install
41
+
42
+ Once published:
43
+
44
+ ```bash
45
+ pip install pin-derive
46
+ ```
47
+
48
+ For development from this repository:
49
+
50
+ ```bash
51
+ cd rust/python
52
+ pip install -e .
53
+ ```
54
+
55
+ ## Usage
56
+
57
+ ```python
58
+ from pin_derive import PinDerive
59
+
60
+ engine = PinDerive() # loads the bundled wasm binary
61
+ snapshot = engine.solve({
62
+ "cells": [
63
+ {"id": "profit", "init": {"lo": 0, "hi": None}},
64
+ {"id": "price", "init": {"lo": 0, "hi": None}},
65
+ {"id": "margin", "init": {"lo": 0, "hi": None}},
66
+ ],
67
+ "relations": [
68
+ {"type": "product", "z": "profit", "x": "price", "y": "margin"},
69
+ ],
70
+ "pins": [
71
+ {"cell": "price", "value": {"lo": 50, "hi": 50}},
72
+ {"cell": "margin", "value": {"lo": 0.2, "hi": 0.2}},
73
+ ],
74
+ })
75
+
76
+ print(snapshot["cells"])
77
+ # profit is derived as 10; price and margin are pinned.
78
+ ```
79
+
80
+ Pass an explicit wasm path only when testing a freshly built development artifact:
81
+
82
+ ```python
83
+ engine = PinDerive("../target/wasm32-unknown-unknown/release/pin_derive_wasm.wasm")
84
+ ```
85
+
86
+ ## Bundled wasm
87
+
88
+ The wheel includes `pin_derive/_pin_derive_wasm.wasm` as package data. The wasm is
89
+ platform-independent, so one pure-Python wheel can work across platforms while
90
+ `wasmtime` supplies the runtime. The binary is committed into the package source and
91
+ rebuilt/copied by release CI before building the wheel; this keeps `pip install
92
+ pin-derive` from requiring a Rust toolchain.
93
+
94
+ To refresh it locally:
95
+
96
+ ```bash
97
+ cd ../
98
+ cargo build --target wasm32-unknown-unknown --release
99
+ cp target/wasm32-unknown-unknown/release/pin_derive_wasm.wasm \
100
+ python/src/pin_derive/_pin_derive_wasm.wasm
101
+ ```
102
+
103
+ ## Full project
104
+
105
+ See the main repository README for the engine model, TypeScript API, Rust port, and
106
+ interactive docs site: <https://github.com/nightwork-dev/pin-derive>.
@@ -0,0 +1,77 @@
1
+ # pin-derive for Python
2
+
3
+ Python bindings for **pin-derive**, a small bidirectional constraint engine: declare
4
+ cells and multidirectional relations, pin any subset, and the rest derive from the
5
+ same network.
6
+
7
+ The TypeScript engine in the repository root is the reference implementation. This
8
+ package runs the Rust/wasm core through the `wasmtime` Python runtime and is held to
9
+ the same conformance fixtures.
10
+
11
+ ## Install
12
+
13
+ Once published:
14
+
15
+ ```bash
16
+ pip install pin-derive
17
+ ```
18
+
19
+ For development from this repository:
20
+
21
+ ```bash
22
+ cd rust/python
23
+ pip install -e .
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ```python
29
+ from pin_derive import PinDerive
30
+
31
+ engine = PinDerive() # loads the bundled wasm binary
32
+ snapshot = engine.solve({
33
+ "cells": [
34
+ {"id": "profit", "init": {"lo": 0, "hi": None}},
35
+ {"id": "price", "init": {"lo": 0, "hi": None}},
36
+ {"id": "margin", "init": {"lo": 0, "hi": None}},
37
+ ],
38
+ "relations": [
39
+ {"type": "product", "z": "profit", "x": "price", "y": "margin"},
40
+ ],
41
+ "pins": [
42
+ {"cell": "price", "value": {"lo": 50, "hi": 50}},
43
+ {"cell": "margin", "value": {"lo": 0.2, "hi": 0.2}},
44
+ ],
45
+ })
46
+
47
+ print(snapshot["cells"])
48
+ # profit is derived as 10; price and margin are pinned.
49
+ ```
50
+
51
+ Pass an explicit wasm path only when testing a freshly built development artifact:
52
+
53
+ ```python
54
+ engine = PinDerive("../target/wasm32-unknown-unknown/release/pin_derive_wasm.wasm")
55
+ ```
56
+
57
+ ## Bundled wasm
58
+
59
+ The wheel includes `pin_derive/_pin_derive_wasm.wasm` as package data. The wasm is
60
+ platform-independent, so one pure-Python wheel can work across platforms while
61
+ `wasmtime` supplies the runtime. The binary is committed into the package source and
62
+ rebuilt/copied by release CI before building the wheel; this keeps `pip install
63
+ pin-derive` from requiring a Rust toolchain.
64
+
65
+ To refresh it locally:
66
+
67
+ ```bash
68
+ cd ../
69
+ cargo build --target wasm32-unknown-unknown --release
70
+ cp target/wasm32-unknown-unknown/release/pin_derive_wasm.wasm \
71
+ python/src/pin_derive/_pin_derive_wasm.wasm
72
+ ```
73
+
74
+ ## Full project
75
+
76
+ See the main repository README for the engine model, TypeScript API, Rust port, and
77
+ interactive docs site: <https://github.com/nightwork-dev/pin-derive>.
@@ -0,0 +1,61 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pin-derive"
7
+ version = "0.4.1"
8
+ description = "Python bindings for the pin-derive bidirectional constraint engine"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Nightwork" }]
14
+ keywords = ["constraints", "solver", "wasm", "wasmtime", "procedural-generation"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Software Development :: Libraries :: Python Modules",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = [
27
+ "wasmtime>=27",
28
+ ]
29
+
30
+ [project.urls]
31
+ Repository = "https://github.com/nightwork-dev/pin-derive"
32
+ Issues = "https://github.com/nightwork-dev/pin-derive/issues"
33
+ Documentation = "https://nightwork-dev.github.io/pin-derive/"
34
+
35
+ [project.optional-dependencies]
36
+ dev = [
37
+ "build>=1.2",
38
+ "mypy>=1.13",
39
+ "pytest>=8",
40
+ "twine>=5",
41
+ ]
42
+
43
+ [tool.mypy]
44
+ strict = true
45
+ files = ["src/pin_derive", "tests/typecheck_api.py"]
46
+
47
+ [tool.hatch.build.targets.wheel]
48
+ packages = ["src/pin_derive"]
49
+ include = [
50
+ "src/pin_derive/_pin_derive_wasm.wasm",
51
+ "src/pin_derive/py.typed",
52
+ ]
53
+
54
+ [tool.hatch.build.targets.sdist]
55
+ include = [
56
+ "LICENSE",
57
+ "README.md",
58
+ "pyproject.toml",
59
+ "src/pin_derive",
60
+ "tests",
61
+ ]
@@ -0,0 +1,326 @@
1
+ """Python bindings for the pin-derive wasm core.
2
+
3
+ The package bundles the platform-independent ``pin_derive_wasm.wasm`` artifact
4
+ and loads it through the ``wasmtime`` runtime. Pass ``wasm_path`` to
5
+ :class:`PinDerive` only when developing against a freshly-built local wasm file.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import struct
12
+ from pathlib import Path
13
+ from typing import Any, Literal, NotRequired, Required, TypedDict, Union, cast
14
+
15
+ from wasmtime import Engine, Instance, Module, Store
16
+
17
+ JsonPrimitive = Union[str, int, float, bool, None]
18
+ JsonValue = Union[JsonPrimitive, list["JsonValue"], dict[str, "JsonValue"]]
19
+ Bound = Union[int, float, None]
20
+ Status = Literal["free", "bounded", "derived", "pinned", "conflicting"]
21
+ Provenance = Literal["user", "choice"] | None
22
+
23
+
24
+ class Interval(TypedDict):
25
+ """A serializable interval. ``None`` means an unbounded side."""
26
+
27
+ lo: Bound
28
+ hi: Bound
29
+
30
+
31
+ class CellSpec(TypedDict, total=False):
32
+ """A cell declaration in the serializable spec."""
33
+
34
+ id: Required[str]
35
+ init: NotRequired[Interval]
36
+ label: NotRequired[str]
37
+
38
+
39
+ class EqualRelation(TypedDict):
40
+ """``a = b``."""
41
+
42
+ type: Literal["equal"]
43
+ a: str
44
+ b: str
45
+
46
+
47
+ class SumRelation(TypedDict):
48
+ """``total = sum(parts)``."""
49
+
50
+ type: Literal["sum"]
51
+ total: str
52
+ parts: list[str]
53
+
54
+
55
+ class ProductRelation(TypedDict):
56
+ """``z = x * y``."""
57
+
58
+ type: Literal["product"]
59
+ z: str
60
+ x: str
61
+ y: str
62
+
63
+
64
+ class AffineRelation(TypedDict):
65
+ """``y = m * x + b``."""
66
+
67
+ type: Literal["affine"]
68
+ y: str
69
+ m: str
70
+ x: str
71
+ b: str
72
+
73
+
74
+ class QuantizeRelation(TypedDict, total=False):
75
+ """``cell`` lies on the ``origin + k * unit`` grid."""
76
+
77
+ type: Required[Literal["quantize"]]
78
+ cell: Required[str]
79
+ unit: Required[float]
80
+ origin: NotRequired[float]
81
+
82
+
83
+ class LteRelation(TypedDict):
84
+ """``a <= b``."""
85
+
86
+ type: Literal["lte"]
87
+ a: str
88
+ b: str
89
+
90
+
91
+ class WithinRelation(TypedDict):
92
+ """The ``xLo..xHi`` interval is contained in ``oLo..oHi``."""
93
+
94
+ type: Literal["within"]
95
+ xLo: str
96
+ xHi: str
97
+ oLo: str
98
+ oHi: str
99
+
100
+
101
+ class MaxPartsRelation(TypedDict):
102
+ """``z = max(parts)`` using the n-ary spelling."""
103
+
104
+ type: Literal["max"]
105
+ z: str
106
+ parts: list[str]
107
+
108
+
109
+ class MaxPairRelation(TypedDict):
110
+ """``z = max(a, b)`` legacy binary spelling."""
111
+
112
+ type: Literal["max"]
113
+ z: str
114
+ a: str
115
+ b: str
116
+
117
+
118
+ class MinPartsRelation(TypedDict):
119
+ """``z = min(parts)`` using the n-ary spelling."""
120
+
121
+ type: Literal["min"]
122
+ z: str
123
+ parts: list[str]
124
+
125
+
126
+ class MinPairRelation(TypedDict):
127
+ """``z = min(a, b)`` legacy binary spelling."""
128
+
129
+ type: Literal["min"]
130
+ z: str
131
+ a: str
132
+ b: str
133
+
134
+
135
+ class ClampRelation(TypedDict):
136
+ """``y = clamp(x, lo, hi)`` with numeric caps."""
137
+
138
+ type: Literal["clamp"]
139
+ y: str
140
+ x: str
141
+ lo: float
142
+ hi: float
143
+
144
+
145
+ class LookupRelation(TypedDict):
146
+ """Monotone table lookup ``y = lookup(x)``."""
147
+
148
+ type: Literal["lookup"]
149
+ y: str
150
+ x: str
151
+ table: list[list[float]]
152
+
153
+
154
+ class CurveRelation(TypedDict):
155
+ """Piecewise-linear curve ``y = curve(x)``."""
156
+
157
+ type: Literal["curve"]
158
+ y: str
159
+ x: str
160
+ table: list[list[float]]
161
+
162
+
163
+ RelationSpec = Union[
164
+ EqualRelation,
165
+ SumRelation,
166
+ ProductRelation,
167
+ AffineRelation,
168
+ QuantizeRelation,
169
+ LteRelation,
170
+ WithinRelation,
171
+ MaxPartsRelation,
172
+ MaxPairRelation,
173
+ MinPartsRelation,
174
+ MinPairRelation,
175
+ ClampRelation,
176
+ LookupRelation,
177
+ CurveRelation,
178
+ ]
179
+
180
+
181
+ class ReplaySpec(TypedDict):
182
+ """A pin or commit replay entry."""
183
+
184
+ cell: str
185
+ value: Interval
186
+
187
+
188
+ class SolveSpec(TypedDict):
189
+ """The JSON spec consumed by :meth:`PinDerive.solve`."""
190
+
191
+ cells: list[CellSpec]
192
+ relations: list[RelationSpec]
193
+ pins: NotRequired[list[ReplaySpec]]
194
+ commits: NotRequired[list[ReplaySpec]]
195
+
196
+
197
+ class SnapshotCell(TypedDict, total=False):
198
+ """A solved cell in the result snapshot."""
199
+
200
+ id: str
201
+ label: str
202
+ value: Interval
203
+ status: Status
204
+ prov: Provenance
205
+
206
+
207
+ class Decision(TypedDict):
208
+ """An underdetermined cell surfaced for a chooser."""
209
+
210
+ id: str
211
+ label: str
212
+ space: Interval
213
+ status: Status
214
+
215
+
216
+ class ConflictOrigin(TypedDict):
217
+ """A conflict origin with the minimum relaxation needed to avoid it."""
218
+
219
+ id: str
220
+ gap: float
221
+
222
+
223
+ class SolveResult(TypedDict):
224
+ """The solved snapshot returned by the wasm core."""
225
+
226
+ converged: bool
227
+ cells: list[SnapshotCell]
228
+ decisions: list[Decision]
229
+ conflicts: list[str]
230
+ conflictOrigins: list[str]
231
+ conflictOriginDetails: NotRequired[list[ConflictOrigin]]
232
+
233
+
234
+ class PinDeriveError(RuntimeError):
235
+ """An error reported by the engine (bad spec or validation failure)."""
236
+
237
+
238
+ _BUNDLED_WASM = "_pin_derive_wasm.wasm"
239
+
240
+
241
+ class PinDerive:
242
+ """A reusable wasmtime-backed pin-derive solver instance."""
243
+
244
+ def __init__(self, wasm_path: str | Path | None = None) -> None:
245
+ path = Path(wasm_path) if wasm_path is not None else Path(__file__).with_name(_BUNDLED_WASM)
246
+ if not path.is_file():
247
+ raise FileNotFoundError(f"pin-derive wasm binary not found: {path}")
248
+
249
+ engine = Engine()
250
+ self._store = Store(engine)
251
+ module = Module.from_file(engine, str(path))
252
+ instance = Instance(self._store, module, [])
253
+ exports = instance.exports(self._store)
254
+ # wasmtime exposes an export as a union of all possible wasm export
255
+ # kinds. These names are fixed by the package's wasm ABI, so narrow
256
+ # them at this boundary rather than leaking that broad union through
257
+ # the public, typed solver API.
258
+ self._memory = cast(Any, exports["memory"])
259
+ self._alloc = cast(Any, exports["pd_alloc"])
260
+ self._dealloc = cast(Any, exports["pd_dealloc"])
261
+ self._solve = cast(Any, exports["pd_solve"])
262
+ self._result_dealloc = cast(Any, exports["pd_result_dealloc"])
263
+
264
+ def solve(self, spec: SolveSpec | str) -> SolveResult:
265
+ """Solve a serializable spec and return the snapshot.
266
+
267
+ ``spec`` may be a typed Python dictionary or a pre-serialized JSON
268
+ string. Engine-side validation errors are raised as
269
+ :class:`PinDeriveError`.
270
+ """
271
+
272
+ data = (spec if isinstance(spec, str) else json.dumps(spec)).encode("utf-8")
273
+ in_ptr = self._alloc(self._store, len(data))
274
+ if data and not in_ptr:
275
+ raise PinDeriveError("wasm input allocation failed")
276
+ try:
277
+ self._memory.write(self._store, data, in_ptr)
278
+ res_ptr = self._solve(self._store, in_ptr, len(data))
279
+ finally:
280
+ self._dealloc(self._store, in_ptr, len(data))
281
+
282
+ if not res_ptr:
283
+ raise PinDeriveError("wasm solver returned a null result pointer")
284
+ try:
285
+ (length,) = struct.unpack("<I", self._memory.read(self._store, res_ptr, res_ptr + 4))
286
+ body = self._memory.read(self._store, res_ptr + 4, res_ptr + 4 + length)
287
+ finally:
288
+ self._result_dealloc(self._store, res_ptr)
289
+
290
+ result = json.loads(body.decode("utf-8"))
291
+ if isinstance(result, dict) and "error" in result:
292
+ raise PinDeriveError(str(result["error"]))
293
+ return cast(SolveResult, result)
294
+
295
+
296
+ __all__ = [
297
+ "Bound",
298
+ "AffineRelation",
299
+ "CellSpec",
300
+ "ClampRelation",
301
+ "ConflictOrigin",
302
+ "CurveRelation",
303
+ "Decision",
304
+ "EqualRelation",
305
+ "Interval",
306
+ "JsonValue",
307
+ "LookupRelation",
308
+ "LteRelation",
309
+ "MaxPairRelation",
310
+ "MaxPartsRelation",
311
+ "MinPairRelation",
312
+ "MinPartsRelation",
313
+ "PinDerive",
314
+ "PinDeriveError",
315
+ "Provenance",
316
+ "ProductRelation",
317
+ "QuantizeRelation",
318
+ "RelationSpec",
319
+ "ReplaySpec",
320
+ "SolveResult",
321
+ "SolveSpec",
322
+ "SnapshotCell",
323
+ "Status",
324
+ "SumRelation",
325
+ "WithinRelation",
326
+ ]
File without changes
@@ -0,0 +1,110 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import pytest
8
+
9
+ from pin_derive import PinDerive, PinDeriveError
10
+
11
+ EPS = 1e-6
12
+
13
+
14
+ def same_bound(actual: float | int | None, expected: float | int | None) -> bool:
15
+ if actual is None or expected is None:
16
+ return actual is expected
17
+ return abs(actual - expected) < EPS
18
+
19
+
20
+ def compare_snapshot(actual: dict[str, Any], expected: dict[str, Any], name: str) -> None:
21
+ assert actual["converged"] == expected["converged"], f"{name}: converged"
22
+ assert [c["id"] for c in actual["cells"]] == [c["id"] for c in expected["cells"]], f"{name}: cell order mismatch"
23
+
24
+ for actual_cell, expected_cell in zip(actual["cells"], expected["cells"]):
25
+ cell_id = expected_cell["id"]
26
+ assert actual_cell["label"] == expected_cell["label"], f"{name}: {cell_id} label"
27
+ assert actual_cell["status"] == expected_cell["status"], f"{name}: {cell_id} status"
28
+ assert actual_cell.get("prov") == expected_cell.get("prov"), f"{name}: {cell_id} prov"
29
+ assert same_bound(actual_cell["value"]["lo"], expected_cell["value"]["lo"]), f"{name}: {cell_id} lo"
30
+ assert same_bound(actual_cell["value"]["hi"], expected_cell["value"]["hi"]), f"{name}: {cell_id} hi"
31
+
32
+ assert [d["id"] for d in actual["decisions"]] == [d["id"] for d in expected["decisions"]], f"{name}: decisions mismatch"
33
+ for actual_decision, expected_decision in zip(actual["decisions"], expected["decisions"]):
34
+ decision_id = expected_decision["id"]
35
+ assert actual_decision["label"] == expected_decision["label"], f"{name}: {decision_id} decision label"
36
+ assert actual_decision["status"] == expected_decision["status"], f"{name}: {decision_id} decision status"
37
+ assert same_bound(actual_decision["space"]["lo"], expected_decision["space"]["lo"]), f"{name}: {decision_id} decision lo"
38
+ assert same_bound(actual_decision["space"]["hi"], expected_decision["space"]["hi"]), f"{name}: {decision_id} decision hi"
39
+
40
+ assert actual["conflicts"] == expected["conflicts"], f"{name}: conflicts mismatch"
41
+ assert actual["conflictOrigins"] == expected["conflictOrigins"], f"{name}: conflictOrigins mismatch"
42
+ assert actual.get("conflictOriginDetails", []) == expected.get("conflictOriginDetails", []), f"{name}: conflictOriginDetails mismatch"
43
+
44
+
45
+ def fixture_cases(fixtures_dir: Path) -> list[Any]:
46
+ files = sorted(fixtures_dir.glob("*.json"))
47
+ assert files, f"no fixtures found in {fixtures_dir}"
48
+ return [pytest.param(path, id=path.stem) for path in files]
49
+
50
+
51
+ @pytest.mark.parametrize("fixture_path", fixture_cases(Path(__file__).resolve().parents[3] / "fixtures"))
52
+ def test_replays_conformance_fixture(fixture_path: Path) -> None:
53
+ case = json.loads(fixture_path.read_text())
54
+ actual = PinDerive().solve(case["spec"])
55
+ compare_snapshot(actual, case["expected"], case["name"])
56
+
57
+
58
+ def test_unknown_relation_type_raises_clean_error() -> None:
59
+ engine = PinDerive()
60
+ with pytest.raises(PinDeriveError, match="unknown type"):
61
+ engine.solve({"cells": [{"id": "a"}], "relations": [{"type": "warp", "a": "a"}]})
62
+
63
+
64
+ def test_result_reports_convergence() -> None:
65
+ result = PinDerive().solve({"cells": [{"id": "a"}], "relations": []})
66
+ assert result["converged"] is True
67
+
68
+
69
+ def test_malformed_json_raises_clean_error() -> None:
70
+ with pytest.raises(PinDeriveError, match="invalid JSON"):
71
+ PinDerive().solve("not-json")
72
+
73
+
74
+ def test_null_wasm_allocator_pointer_raises_before_memory_access() -> None:
75
+ engine = PinDerive.__new__(PinDerive)
76
+ engine._store = object()
77
+ engine._alloc = lambda *_args: 0
78
+
79
+ with pytest.raises(PinDeriveError, match="wasm input allocation failed"):
80
+ engine.solve({"cells": [], "relations": []})
81
+
82
+
83
+ def test_null_wasm_result_pointer_raises_after_input_cleanup() -> None:
84
+ events: list[str] = []
85
+
86
+ class FakeMemory:
87
+ def write(self, *_args: object) -> None:
88
+ events.append("write")
89
+
90
+ engine = PinDerive.__new__(PinDerive)
91
+ engine._store = object()
92
+ engine._memory = FakeMemory()
93
+ engine._alloc = lambda *_args: 17
94
+ engine._solve = lambda *_args: 0
95
+ engine._dealloc = lambda *_args: events.append("input_dealloc")
96
+ engine._result_dealloc = lambda *_args: (_ for _ in ()).throw(AssertionError("null result was deallocated"))
97
+
98
+ with pytest.raises(PinDeriveError, match="wasm solver returned a null result pointer"):
99
+ engine.solve({"cells": [], "relations": []})
100
+ assert events == ["write", "input_dealloc"]
101
+
102
+
103
+ def test_unknown_pin_target_raises_clean_error() -> None:
104
+ engine = PinDerive()
105
+ with pytest.raises(PinDeriveError, match="no cell"):
106
+ engine.solve({
107
+ "cells": [{"id": "a"}],
108
+ "relations": [],
109
+ "pins": [{"cell": "ghost", "value": {"lo": 1, "hi": 1}}],
110
+ })
@@ -0,0 +1,51 @@
1
+ """Static API examples checked with mypy.
2
+
3
+ This module is intentionally not a runtime test. It keeps representative
4
+ specifications in the test tree so CI can run ``mypy --strict`` against the
5
+ public package and catch drift between the JSON contract and its annotations.
6
+ """
7
+
8
+ from pin_derive import PinDerive, SolveSpec
9
+
10
+
11
+ VALID_SPEC: SolveSpec = {
12
+ "cells": [
13
+ {"id": "x", "init": {"lo": 0, "hi": None}},
14
+ {"id": "y"},
15
+ {"id": "z"},
16
+ {"id": "xLo"},
17
+ {"id": "xHi"},
18
+ {"id": "oLo"},
19
+ {"id": "oHi"},
20
+ ],
21
+ "relations": [
22
+ {"type": "equal", "a": "x", "b": "y"},
23
+ {"type": "sum", "total": "z", "parts": ["x", "y"]},
24
+ {"type": "product", "z": "z", "x": "x", "y": "y"},
25
+ {"type": "affine", "y": "y", "m": "x", "x": "x", "b": "z"},
26
+ {"type": "quantize", "cell": "x", "unit": 5, "origin": -1},
27
+ {"type": "lte", "a": "xLo", "b": "xHi"},
28
+ {"type": "within", "xLo": "xLo", "xHi": "xHi", "oLo": "oLo", "oHi": "oHi"},
29
+ {"type": "max", "z": "z", "parts": ["x", "y"]},
30
+ {"type": "max", "z": "z", "a": "x", "b": "y"},
31
+ {"type": "min", "z": "z", "parts": ["x", "y"]},
32
+ {"type": "min", "z": "z", "a": "x", "b": "y"},
33
+ {"type": "clamp", "y": "y", "x": "x", "lo": 0, "hi": 10},
34
+ {"type": "lookup", "y": "y", "x": "x", "table": [[0, 0], [1, 2]]},
35
+ {"type": "curve", "y": "y", "x": "x", "table": [[0, 0], [1, 2]]},
36
+ ],
37
+ "pins": [{"cell": "x", "value": {"lo": 1, "hi": 1}}],
38
+ }
39
+
40
+
41
+ def solve_inline_literal() -> None:
42
+ """Inline dictionaries remain ergonomic for callers."""
43
+
44
+ result = PinDerive().solve(
45
+ {
46
+ "cells": [{"id": "x"}, {"id": "y"}],
47
+ "relations": [{"type": "sum", "total": "y", "parts": ["x"]}],
48
+ }
49
+ )
50
+ assert result["converged"]
51
+