diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 92445f5f..6bbf513b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,9 @@ jobs: run: npm run test:types - name: Build run: npm run build + - name: Full release checks + if: github.event_name == 'workflow_dispatch' + run: CI=1 npm run check:all test: if: github.event_name != 'schedule' @@ -78,6 +81,60 @@ jobs: files: ./coverage/lcov.info fail_ci_if_error: false + isolated-consumer: + if: github.event_name != 'schedule' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: 22 + cache: npm + - name: Setup Python + uses: actions/setup-python@v6 + with: + python-version: '3.11' + - name: Install dependencies + run: npm ci --prefer-offline --no-audit + - name: Build package candidate + run: npm run build + - name: Run isolated consumer check + env: + CI: '1' + run: npx vitest run --config vitest.isolated-consumer.config.ts + + pyodide-browser: + if: github.event_name != 'schedule' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: 22 + cache: npm + - name: Setup Python + uses: actions/setup-python@v6 + with: + python-version: '3.11' + - name: Install dependencies + run: npm ci --prefer-offline --no-audit + - name: Install tywrap-ir + run: python -m pip install -e tywrap_ir + - name: Build package + run: npm run build + - name: Install Chromium + run: npx playwright install --with-deps chromium + - name: Fetch locked NumPy asset + run: node scripts/fetch-pyodide-package.mjs numpy + - name: Record pinned runtime evidence + run: node scripts/print-pyodide-ci-evidence.mjs + - name: Run real Pyodide and browser checks + env: + CI: '1' + run: npx vitest run --config vitest.pyodide.config.ts + python-suite-core: if: github.event_name != 'schedule' runs-on: ubuntu-latest @@ -101,7 +158,7 @@ jobs: - name: Run Python codec and frame tests run: | python -m pip install pytest - python -m pytest test/python/test_bridge_codec.py test/python/test_frame_codec.py + python -m pytest test/python/test_bridge_codec.py test/python/test_bridge_core.py test/python/test_frame_codec.py python-suite-data: if: github.event_name != 'schedule' @@ -223,11 +280,12 @@ jobs: PIP_PROGRESS_BAR: 'off' run: | python -m pip install -e tywrap_ir - python -m pip install numpy==2.3.5 pandas==3.0.2 pyarrow==24.0.0 scipy==1.16.3 scikit-learn==1.8.0 + python -m pip install numpy==2.3.5 pandas==3.0.2 pyarrow==24.0.0 scipy==1.16.3 scikit-learn==1.8.0 pydantic==2.7.4 python -m pip install torch==2.10.0 --index-url https://download.pytorch.org/whl/cpu - name: Run pinned scientific menagerie env: TYWRAP_CODEC_PYTHON: python + TYWRAP_REQUIRE_TORCH_CONFORMANCE: '1' run: npm run test:menagerie os: @@ -359,6 +417,8 @@ jobs: needs: - lint - test + - isolated-consumer + - pyodide-browser - python-suite-core - python-suite-data - living-app @@ -373,6 +433,8 @@ jobs: fail=0 if [ "${{ needs.lint.result }}" != "success" ]; then echo "::error::lint: ${{ needs.lint.result }}"; fail=1; fi if [ "${{ needs.test.result }}" != "success" ]; then echo "::error::test: ${{ needs.test.result }}"; fail=1; fi + if [ "${{ needs.isolated-consumer.result }}" != "success" ]; then echo "::error::isolated-consumer: ${{ needs.isolated-consumer.result }}"; fail=1; fi + if [ "${{ needs.pyodide-browser.result }}" != "success" ]; then echo "::error::pyodide-browser: ${{ needs.pyodide-browser.result }}"; fail=1; fi if [ "${{ needs.python-suite-core.result }}" != "success" ]; then echo "::error::python-suite-core: ${{ needs.python-suite-core.result }}"; fail=1; fi if [ "${{ needs.python-suite-data.result }}" != "success" ]; then echo "::error::python-suite-data: ${{ needs.python-suite-data.result }}"; fail=1; fi if [ "${{ needs.living-app.result }}" != "success" ]; then echo "::error::living-app: ${{ needs.living-app.result }}"; fail=1; fi diff --git a/.github/workflows/published-consumer.yml b/.github/workflows/published-consumer.yml new file mode 100644 index 00000000..aaf0b7e1 --- /dev/null +++ b/.github/workflows/published-consumer.yml @@ -0,0 +1,46 @@ +name: Published consumer + +# Run only after both exact versions are public on npm and PyPI. +# From the released repository ref: +# gh workflow run published-consumer.yml --ref \ +# -f npm_version= -f pypi_version= +on: + workflow_dispatch: + inputs: + npm_version: + description: Exact published tywrap version on npm + required: true + type: string + pypi_version: + description: Exact published tywrap-ir version on PyPI + required: true + type: string + +run-name: npm ${{ inputs.npm_version }} and PyPI ${{ inputs.pypi_version }} + +permissions: + contents: read + +jobs: + published-consumer: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: 22 + cache: npm + - name: Setup Python + uses: actions/setup-python@v6 + with: + python-version: '3.11' + - name: Install test runner + run: npm ci --ignore-scripts --prefer-offline --no-audit --no-fund + - name: Check published packages in a clean consumer + env: + CI: '1' + TYWRAP_CONSUMER_MODE: published + TYWRAP_PUBLISHED_NPM_VERSION: ${{ inputs.npm_version }} + TYWRAP_PUBLISHED_PYPI_VERSION: ${{ inputs.pypi_version }} + run: npx vitest run --config vitest.isolated-consumer.config.ts diff --git a/ROADMAP.md b/ROADMAP.md index 9fadc908..06f268c3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -8,6 +8,17 @@ The scientific codec envelope reference lives in ## Recent releases +### v0.10.0: scientific codec correctness + +`v0.10.0` shipped on 13 July 2026. Scientific values now compose inside +containers, and decoded envelopes validate their shape, dtype, and provenance. +JSON ndarray and pandas conversions reject values they cannot preserve. +Torch bfloat16 values use exact float32 storage, and Arrow supports scalar arrays. +The pinned scientific menagerie checks the supported cases and explicit failures. + +The Python package stayed at `tywrap-ir` 0.3.0 with IR schema 0.4.0. +See [the changelog](./CHANGELOG.md#0100-2026-07-13) for compatibility details. + ### v0.9.0: typed value-RPC `v0.9.0` narrowed tywrap to one job done well: typed value-RPC between @@ -113,9 +124,24 @@ and bridge live. ## Now -The typed value-RPC contract pass (#260) is complete as of `v0.9.0`, and the -scientific data plane (#237) as of `v0.8.0`. The next release theme is not yet -locked; candidates are drawn from **Later** below. +The next planned release is `v0.11.0`, tracked in #342 and #334. It must reject +unsafe Python integers before JSON encoding and decode Arrow float16 storage +as numeric values. Generated wrappers must pass a clean consumer installation +test with the candidate npm and Python packages. + +Architecture work in #345 joins callable resolution with shared value contracts. +Its proof covers safe integers, float16 arrays reused by Torch, and overloads +that return nested records. Independent tests must exercise generation, +TypeScript compilation, execution, decoding, and return validation. + +Overload preservation and coroutine execution have separate acceptance criteria +in #336 and #338. Actual Pyodide and browser tests in #341 must pass before any +browser coroutine claim. The release scope will record only accepted behavior. + +Bigint transport, dataclass values, and explicitly bound clients remain bounded +design prototypes in #337, #339, and #340. Completing their designs does not +establish general production support. The current integer release policy remains +rejection outside the JavaScript safe range. See [docs/codec-envelopes.md](./docs/codec-envelopes.md) for the scientific codec envelope reference. diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 6260160b..8c5ef801 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -27,6 +27,7 @@ export default defineConfig({ text: 'Guide', items: [ { text: 'Getting Started', link: '/guide/getting-started' }, + { text: 'Migrating to 0.11', link: '/guide/migrating-to-0-11' }, { text: 'Agent Adoption', link: '/guide/agent-adoption' }, { text: 'Configuration', link: '/guide/configuration' }, { text: 'Watch & Reload', link: '/guide/dev-reload' }, diff --git a/docs/guide/migrating-to-0-11.md b/docs/guide/migrating-to-0-11.md new file mode 100644 index 00000000..4a1cc4a6 --- /dev/null +++ b/docs/guide/migrating-to-0-11.md @@ -0,0 +1,132 @@ +# Migrating to 0.11 + +This guide covers the planned 0.11 changes. The release is not published yet. + +## Large Python integers + +Python `int` results still use TypeScript `number`. The supported range is +`-9007199254740991` through `9007199254740991`, inclusive. + +Earlier versions could round larger integers when JavaScript parsed the response. +The new serializer rejects those values before writing JSON. This applies to root +results, nested containers, supported NumPy scalars, and model dumps. + +For example, a result containing `{"items": [9007199254740993]}` now fails at +`result.items[0]`. The error identifies the unsafe value and suggests an explicit +string or an Arrow integer column. + +Return a string when the value represents an identifier or must remain an exact +decimal integer: + +```python +def large_identifier() -> str: + return str(9007199254740993) +``` + +The generated return type is `Promise`. Convert that string with +JavaScript `BigInt` if your application needs integer arithmetic. Validate any +string that comes from an untrusted source before using it. + +Keep integer columns in Arrow tables when you need the existing Arrow int64 +representation. Arrow int64 remains exact and can decode as JavaScript `bigint`. +JSON fallback does not provide that representation and rejects unsafe integers. + +Booleans and finite floats remain supported. Converting an integer to a Python +`float` can lose precision before tywrap receives it. Use a string when exactness +matters. Tagged bigint transport remains a separate design proposal. + +## NumPy and Torch float16 + +The Arrow decoder now converts float16 storage words into their numeric values +before reshaping the result. For example, `[15872, 49280]` becomes the intended +`[1.5, -2.25]`. Remove application code that manually decodes those storage words. + +The conversion preserves signed zero, finite subnormal values, and finite extrema. +NumPy arrays and nested Torch tensors use the same conversion. Non-finite results +continue to reject under the existing policy. + +The scientific envelope format, JSON fallback, and Arrow int64 behavior stay +compatible. Torch bfloat16 keeps its existing float32 transport conversion. + +## Return types that cannot be validated + +An unresolved Python `object` result now produces `Promise`. Python +objects can include strings and numbers, which TypeScript's `object` type excludes. + +An unresolved generic result also becomes `unknown`. Earlier wrappers could +declare `Promise` while accepting any returned value. A generic input remains +generic, but its type alone cannot prove that Python returned the same type. +This also applies when the unresolved type parameter appears in a nested result. + +Generation reports the unresolved conversion. `--fail-on-warn` rejects that +diagnostic. Use a supported concrete return annotation or overload when the +Python API has a known result type. Otherwise, check the value before using it: + +```ts +const result = await generatedFunction(input); +if (typeof result !== 'string') { + throw new TypeError('Expected a string result'); +} +console.log(result.toUpperCase()); +``` + +The current value contract does not resolve every Python annotation. For example, +`Literal` results become `unknown`, while their existing literal checks remain. +Other unresolved returns retain available marker, container or record checks. +These partial checks do not prove a precise TypeScript return type. +Type-only Protocol methods keep their declared generic signatures. + +Supported string and integer overloads retain their corresponding return types. +Use Python 3.11 or later to extract registered overloads. Python 3.10 keeps the +implementation signature when its typing module cannot expose the overloads. + +## Coroutine results + +The updated Node and Pyodide bridges await Python coroutine results. Generated +wrappers use the function's resolved result type, such as `Promise`. +Upgrade the generator and runtime together, then regenerate wrappers. + +An HTTP client still depends on its server. Use a compatible server that awaits +Python results; upgrading the TypeScript client does not update that server. + +## Regenerate wrappers + +After these versions are published, upgrade both packages: + +```bash +npm install tywrap@0.11.0 +python3 -m pip install --upgrade tywrap-ir==0.3.1 +``` + +Use the Python executable selected by `runtime.node.pythonPath` and +`runtime.node.virtualEnv` instead of `python3` when your configuration differs. +The new extractor captures generic parameters used only in overload annotations. +Its IR schema remains `0.4.0`, so the schema check alone cannot detect an older +extractor or an older saved contract. + +Extract fresh IR when regenerating: + +```bash +npx tywrap generate --no-cache +``` + +This bypasses the on-disk IR cache. It does not replace existing cache entries. +If you enable caching again, first remove the old generated IR files from +`.tywrap/cache` so generation extracts and caches the updated contracts. + +If you use `contractInput`, temporarily omit it to extract fresh contracts with +the updated Python package. Review each new `.contract.json` in your +output directory. Replace the corresponding pinned input file with that contract, +or point `contractInput` to the new file. Then restore the setting. +The `--no-cache` option does not replace a pinned input contract. + +Regenerate wrappers with the upgraded generator. Python `int` return validators +then check the safe integer range as well as the JavaScript value type. +Regeneration also applies the reviewed callable-contract diagnostics. + +Update any tests that expected a rounded integer or float16 storage words. +Assert the corrected value or the specific conversion error instead. + +Run your generated calls against the upgraded runtime before deploying them. +An old wrapper cannot add the new generated return checks by itself, although the +upgraded Python serializer still rejects unsafe integer results. diff --git a/docs/guide/runtimes/browser.md b/docs/guide/runtimes/browser.md index 20035c14..7c52311e 100644 --- a/docs/guide/runtimes/browser.md +++ b/docs/guide/runtimes/browser.md @@ -1,4 +1,4 @@ -# Browser Runtime Guide +# Browser runtime guide Run Python in the browser using Pyodide WebAssembly. @@ -9,14 +9,16 @@ Run Python in the browser using Pyodide WebAssembly. - Pre-built packages via Pyodide - Works well for notebooks, demos, and client-side analysis -## Quick Start +## Quick start ### Install + ```bash npm install tywrap pyodide ``` ### Configure + ```json { "pythonModules": { @@ -25,7 +27,7 @@ npm install tywrap pyodide }, "runtime": { "pyodide": { - "indexURL": "https://cdn.jsdelivr.net/pyodide/v0.28.0/full/", + "indexURL": "https://cdn.jsdelivr.net/pyodide/v0.28.1/full/", "packages": ["numpy", "matplotlib", "scipy"] } } @@ -33,14 +35,15 @@ npm install tywrap pyodide ``` ### Use + ```ts import { PyodideBridge } from 'tywrap/pyodide'; import { setRuntimeBridge } from 'tywrap/runtime'; import { array } from './generated/numpy.generated.js'; const bridge = new PyodideBridge({ - indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.28.0/full/', - packages: ['numpy'] + indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.28.1/full/', + packages: ['numpy'], }); setRuntimeBridge(bridge); @@ -49,7 +52,7 @@ const arr = await array([1, 2, 3]); console.log(arr); ``` -## Configuration Options +## Configuration options ```ts interface PyodideBridgeOptions { @@ -58,19 +61,25 @@ interface PyodideBridgeOptions { } ``` -The `packages` array is loaded during initialization. For additional package +The bridge loads the `packages` array during initialization. For additional package loading, rely on Pyodide directly. -## Data Transport +## Data transport -Arrow envelopes are supported in the browser if you register an Arrow decoder (Node auto-registers when `apache-arrow` is installed): +PyodideBridge uses JSON transport. It converts supported NumPy arrays and pandas +tables to JSON envelopes. It does not send Arrow payloads. -```ts -import { registerArrowDecoder } from 'tywrap'; +See [codec envelopes](../../codec-envelopes.md) for supported values and transport limits. -registerArrowDecoder(bytes => bytes); -``` +## Build integration + +Run `tywrap generate` during your build. Load Pyodide at runtime from a CDN or your own server. + +## Test coverage -## Build Integration +The unit tests mock the Pyodide loader. The cross-backend suite runs the shared +Python bootstrap under CPython. Neither check proves browser execution. -Run `tywrap generate` during your build and load Pyodide at runtime (CDN or self-hosted). +Required CI also runs the pinned Pyodide package in Node WebAssembly and a +Chromium smoke test. The browser test loads local Pyodide assets and executes a +generated wrapper. diff --git a/docs/guide/runtimes/http.md b/docs/guide/runtimes/http.md index c5cca83f..e91f556d 100644 --- a/docs/guide/runtimes/http.md +++ b/docs/guide/runtimes/http.md @@ -49,6 +49,11 @@ setRuntimeBridge( payloads. You must provide a compatible server endpoint. Each call is an independent POST request because the protocol is stateless. +Generated async callables have typed results when their return annotations have +supported value conversions. The in-repo Node and Pyodide bridges await Python +coroutines. For `HttpBridge`, your server must await coroutines before it sends +the result. `HttpBridge` cannot verify a remote server's coroutine support. + tywrap does not include an HTTP server. See the [API reference](/reference/api/) for the expected request and response format. diff --git a/docs/maintainers/architecture.md b/docs/maintainers/architecture.md index fac5902d..395f0c2b 100644 --- a/docs/maintainers/architecture.md +++ b/docs/maintainers/architecture.md @@ -10,8 +10,9 @@ the declared return schema. | Stage | Owners | Invariant | | --- | --- | --- | | Python analysis | `tywrap_ir/tywrap_ir/__main__.py`, `tywrap_ir/tywrap_ir/` | The extractor emits JSON typed IR for the requested module. | -| IR contract | `src/tywrap.ts`, `src/types/` | A contract has the expected module and `ir_version`. The current version is `0.4.0`. | -| Wrapper generation | `src/core/generator.ts`, `src/core/emit-call.ts`, `src/core/mapper.ts` | Generated calls carry a `ReturnSchema` that represents the Python return annotation. | +| IR contract | `src/core/ir-contract.ts`, `src/tywrap.ts` | Pure validation checks the complete IR structure and schema version `0.4.0`; generation checks the requested module. | +| Callable compilation | `src/core/callable-compiler.ts`, `src/contracts/value-contract.ts` | Resolved contracts describe arguments, overloads, conversion, validation, capabilities and diagnostics without I/O. | +| Wrapper generation | `src/core/generator.ts`, `src/core/emit-call.ts` | Declarations, call wrappers and return validators consume the resolved callable contracts. | | Runtime transport | `src/runtime/node.ts`, `src/runtime/subprocess-transport.ts`, `src/runtime/frame-codec.ts`, `runtime/python_bridge.py` | Node subprocess requests use JSONL and use `tywrap-frame/1` when a message exceeds one line. | | Python dispatch and encoding | `runtime/tywrap_bridge_core.py`, `runtime/safe_codec.py` | The bridge validates protocol input, then dispatches the requested call and returns JSON-safe values or versioned envelopes. | | JavaScript decoding | `src/utils/codec.ts`, `src/runtime/bridge-codec.ts` | Envelope shape and payload domains are checked before a decoded value reaches application code. | @@ -19,22 +20,32 @@ the declared return schema. ## IR and generated contracts -`generate()` in `src/tywrap.ts` invokes `python -m tywrap_ir --module `. -It validates the returned object before passing it to `CodeGenerator`, which -produces the wrapper source; `src/tywrap.ts` then writes -`.generated.ts` and the stable `.contract.json` beside it. The contract omits extractor metadata, -sorts object keys, and records the pinned IR representation. +`generate()` in `src/tywrap.ts` owns Python discovery, IR caching and file writes. +When it needs fresh IR, it invokes `python -m tywrap_ir --module `. +The pure IR validator checks the complete returned structure with located errors. +`compileContract()` resolves that IR using explicit conversion rules and runtime +capabilities. It does not access the filesystem, Python interpreter or runtime registry. + +The generator emits wrappers and declarations from those resolved contracts. +`generate()` writes `.generated.ts` and a stable `.contract.json`. +The saved contract contains canonical Python IR, not the resolved callable model. +It omits extractor metadata and sorts object keys. `contractInput` changes the source of IR. Instead of starting Python, generation -reads a saved contract and applies the same module and version validation. This +reads a saved contract and applies the same complete IR validation. This supports reproducible generation. A version mismatch is a hard failure: update the matching package pair and regenerate the contract. -`src/core/generator.ts` maps annotations to TypeScript and emits one -`createReturnValidator()` call per generated callable. Return schemas cover -primitive values, containers, definitions, and scientific markers. The -wrapper calls the active bridge and validates the resolved value before its -promise resolves. +The callable contract connects a result's logical type, decoded representation +and validator. A precise return declaration requires a supported conversion and +validation path. Unresolved results become `unknown` with diagnostics while +retaining available partial runtime checks. + +The generator emits `createReturnValidator()` calls from these contracts. +Return schemas cover primitives, containers, definitions and scientific markers. +Each wrapper calls the active bridge and validates the decoded result before its +promise resolves. See [callable contracts](./callable-contracts.md) for compiler +boundaries and [value contracts](./value-contracts.md) for conversion policy. ## Runtime bridges @@ -49,6 +60,9 @@ not edit it directly. Regenerate it from `runtime/tywrap_bridge_core.py` with the repository script. Pyodide uses JSON codec envelopes because pyarrow is not available in WASM. +The bridge awaits Python call results under the event loop owned by each +backend. See [coroutine calls](./coroutines.md) for timeout and disposal rules. + `HttpBridge` sends the same RPC and codec concepts to a remote Python service. The transport owns HTTP concerns while the codec and return validator preserve the client-side invariants. @@ -78,10 +92,12 @@ the required nested ndarray inside a torch envelope. `src/runtime/validators.ts` validates the value after decoding. A mismatch throws `BridgeValidationError` with the call site, declared type, and received -shape. Scientific values retain non-enumerable provenance from their envelope. +shape. Scientific values retain provenance from their envelope. Scalar scientific +results use per-call provenance because a JavaScript number cannot hold metadata. The validator checks the marker and, when the schema declares them, dimensions -and dtype without walking Arrow payload data. `unknown`, `void`, and `Any` -returns deliberately receive no runtime check. +and dtype without walking Arrow payload data. Explicit `unknown`, `void`, and +`Any` schemas perform no check. A result whose declaration became `unknown` can +still retain partial checks from its original annotation. ## One call end to end diff --git a/docs/maintainers/callable-contracts.md b/docs/maintainers/callable-contracts.md new file mode 100644 index 00000000..8de1ea45 --- /dev/null +++ b/docs/maintainers/callable-contracts.md @@ -0,0 +1,114 @@ +# Callable compilation contracts + +`tywrap_ir` emits IR 0.4. `validateIrContract()` checks required fields in +unknown JSON. Each diagnostic has a JSON path. Validation stops after 100,000 +array entries. + +`compileContract()` is an internal pure step. It accepts validated IR, +exported-name selection, value conversions, capabilities, and a generator. It +maps callable types from the validated IR. The selection input cannot change +those types. It returns the resolved module, callable records, diagnostics, and +TypeScript and declaration content. + +The compiler does not read files. It does not start Python. It does not read a +cache. It does not write files. It does not access a runtime registry. + +`generate()` owns Python discovery, cache reads, output comparison, and writes. +It validates IR and maps annotations, then calls `compileContract()` before +emission. Offline contract files omit extractor metadata for stable bytes. The +reader restores an empty metadata object. + +## Resolved callable data + +The compiler records each parameter and result, including overloads. Each record +has a Python type, direction, source path, and conversion result. One resolved +module model serves declarations, call wrappers, and return validators. + +Each value conversion uses revision 2 of +[value-contracts.v2.json](value-contracts.v2.json). Do not infer a wire rule +from the TypeScript type. + +| Case | Result | +| --------------------- | ------------------------------------------------------------------------------------- | +| `int` | JSON number, JavaScript number, safe-integer constraint | +| `bytes` | Existing base64 envelope, decoded as `Uint8Array` | +| nested `dict[str, T]` | JSON record with the child conversion at every value path | +| `str \| int` | Selected union alternative with one child contract per option | +| `tuple[int, str]` | Exact JSON array with a contract for each index | +| float16 ndarray | Existing Arrow or JSON-fallback envelope, decoded as a numeric scalar or nested array | +| float16 Torch tensor | Outer `torch.float16` envelope with a nested `float16` ndarray | + +The compiler requires an explicit float16 dtype. An untyped ndarray or Torch +tensor stays unresolved. + +For an evaluated PyTorch annotation, use `torch.HalfTensor`. The compiler +accepts this exact class and leaves other Torch tensor classes unresolved. + +NumPy can spell `NDArray[np.float16]` as +`numpy.ndarray[tuple[Any, ...], numpy.dtype[numpy.float16]]`. The compiler reads +the dtype argument, not the shape wildcard. Only a supported scientific result +clears its matching external-annotation IR warning. Other external annotations +remain warnings. + +The codec records scalar ndarray dtype and rank for one call. A generated return +validator accepts a scalar only with matching proof. Nested proof follows its +parent and array index or record key. Array index `0` and `"0"` refer to the +same child. Equal numbers from separate calls do not share proof. Array and +tensor objects keep their identity-based marker proof. + +The compiler keeps Arrow int64 behavior outside this prototype. Existing Arrow +int64 values can decode as `bigint`. + +Selected local non-generic `TypedDict` classes use revision-2 record contracts +when every field has a supported conversion. Nested records and selected simple +aliases compose through the same resolver. Foreign and recursive names remain +unresolved. + +## Diagnostics and fallback + +Known unsupported cases create error diagnostics. The compiler changes the +affected generated type to `unknown`. `generate()` returns each diagnostic as a +warning, so `--fail-on-warn` rejects strict builds. + +- The default compiler capability covers coroutine execution in the in-repo Node + and Pyodide bridges. A caller can mark this capability unavailable when it + uses an older or custom bridge. The compiler then emits `unknown` and an error + diagnostic for async results. +- Dataclasses require an adapter owned by #339. The default capability stays + unavailable. An explicit output record conversion can use the adapter + capability when enabled. +- Non-string record keys require an explicit conversion. + +Unresolved annotations create warning diagnostics. Their result type is +`unknown`, including an output that contains `object` or a type variable. Python +`object` can hold a primitive value. A type variable has no validated conversion +to the decoded result. Neither annotation justifies a precise TypeScript return. + +The compiler keeps an existing best-effort return check when it widens a +declaration. For example, an unresolved `list[object]` still rejects a non-array +result, and a `DataFrame` annotation still requires a decoded marker. + +`Literal` returns keep their exact-value validator, but stay `unknown` until a +literal value contract exists. Unresolved literal overloads cannot select a +precise return at runtime. + +IR overload signatures stay separate from the implementation signature. The +extractor collects type variables from overload annotations. Generated +declarations retain each input-to-result relation. The hidden TypeScript +implementation accepts `unknown` values so it can cover every declared overload. + +At runtime, the wrapper selects the first supported overload that matches bound +arguments. This follows TypeScript declaration order. The compiler warns when +overload inputs may overlap, including an omitted optional argument. Python 3.10 +cannot expose registered overloads through `typing.get_overloads`; it keeps the +implementation signature and emits an IR warning. + +## Deferred work + +Revision 2 does not describe references or recursive aliases. The compiler +reports these cases as unresolved. A later value-contract revision can give them +a supported conversion. + +The client-binding work may consume the resolved callable model later. It must +remain opt-in. It must not add files to default generation or mutate the global +runtime registry. diff --git a/docs/maintainers/client-binding-design.md b/docs/maintainers/client-binding-design.md new file mode 100644 index 00000000..30f1673f --- /dev/null +++ b/docs/maintainers/client-binding-design.md @@ -0,0 +1,171 @@ +# Explicit runtime binding design + +Status: the bounded [#340](https://github.com/bbopen/tywrap/issues/340) prototype at `65bed95` passed independent review and CI. Public generation support remains future work. + +## Proposed client API + +The prototype adds `.generated.client.ts` beside the existing wrapper. The existing `.generated.ts` keeps its exports. + +Tests invoke the internal prototype renderer directly. There is no public generation option. Default `generate()` output remains unchanged. + +```ts +import { NodeBridge } from 'tywrap/node'; +import { bindRuntime } from './generated/math.generated.client.js'; + +const bridgeA = new NodeBridge({ pythonPath: '/env/a/bin/python' }); +const bridgeB = new NodeBridge({ pythonPath: '/env/b/bin/python' }); +const a = bindRuntime(bridgeA); +const b = bindRuntime(bridgeB); + +const [left, right] = await Promise.all([a.api.sqrt(9), b.api.sqrt(16)]); +await a.api.sqrt(25); +await b.api.sqrt(36); + +a.dispose(); +b.dispose(); +await Promise.all([bridgeA.dispose(), bridgeB.dispose()]); +``` + +`bindRuntime(runtime: BoundRuntime)` captures the supplied bridge. It returns a handle with `api` and `dispose()`. `BoundRuntime` contains only the bridge's `call` method. A full bridge also satisfies this type. + +Python names stay inside `api`. For example, a Python `dispose` function becomes `handle.api.dispose()`. It cannot replace handle disposal. + +The companion module also avoids collisions with generated names such as `Client` and `createClient` in the existing module. + +`api` contains generated module functions. It contains plain namespaces for supported class and static methods. + +```ts +const pets = bindRuntime(petBridge); +const dog = await pets.api.Pet.createDog('Rex'); +``` + +`Pet` above is a namespace of calls. It is not a Python object handle or a JavaScript constructor. + +## Types and generated code + +The companion must emit each signature from the same Python model as the legacy wrapper. It must preserve each overload and generic parameter. + +```ts +export interface BoundApi { + identity(value: T): Promise; + select(value: number): Promise; + select(value: string): Promise; + scale(value: number): Promise; + scale(value: number, factor?: number): Promise; + Client: { + label(value: string): Promise; + }; +} +``` + +This block shows the required declaration form for the fixture. `select` has two Python `@overload` branches. + +The compiler keeps `identity`'s generic input. Its result is `unknown` because the runtime cannot validate an unresolved type variable. Bound and legacy calls must emit that same return type. + +`scale` has a trailing optional Python parameter. These are separate typing checks. + +Actual signatures follow the source module. `Parameters<>` and `ReturnType<>` cannot define `BoundApi` because they lose overloads. + +The compiler should emit one private implementation for each callable. That implementation shapes arguments, applies guards, calls the bridge, and validates the result. + +The legacy entrypoint chooses `getRuntimeBridge()` for each call. A bound entrypoint uses its captured bridge. Both entrypoints call the same private implementation. + +The private implementation lives in `.generated.core.ts`. The existing wrapper and companion import it in the prototype. + +The prototype renderer generates both forms from one compiled module and one generator. It does not accept a separate template. It rejects source maps until each emitted file can carry its own map. + +The compiler must allocate collision-free import aliases. Python names can map to helper-like TypeScript names. + +A future public generation option could add `bindingPrototype` to `GeneratedCode`: + +```ts +interface GeneratedCode { + typescript: string; + declaration: string; + bindingPrototype?: { + core: { typescript: string; declaration: string }; + client: { typescript: string; declaration: string }; + }; +} +``` + +The prototype test writes the renderer's three source files to a temporary directory. The proposed `GeneratedCode` field is not implemented. + +Production integration must add both files to `emitOrCompareFiles()`. It must handle optional declarations, source maps, and configured output formats. + +The proposed names end in `.generated.core.ts` and `.generated.client.ts`. They cannot equal another module's `.generated.ts` path. + +The compiler must still check all emitted paths for duplicates before writing. It must never overwrite an existing file with another module's artifact. + +Only configured Python modules enter the generation loop. Core and companion files are output artifacts, never new input modules. + +## Ownership and failure + +The supplied bridge is borrowed. `handle.dispose()` closes only that handle. It never calls `runtime.dispose()` or changes the global registry. + +Disposal is idempotent. A call started after disposal rejects with `BridgeDisposedError`. A call started before disposal keeps its selected bridge. + +If the owner disposes the bridge during a call, the bridge controls that call's result. The handle does not extend the bridge lifetime. + +Argument, conversion, bridge, and return-validation failures reject the generated promise. They do not close the handle or affect another handle. + +The owner disposes each bridge once all users finish. Two handles may borrow one bridge without taking joint ownership. + +## Reload + +An existing bound handle never changes its bridge. The caller creates a new handle from `reloader.current()` after a successful reload. + +The current reloader disposes its previous bridge after a swap. Calls on an old handle then follow that bridge's disposed behavior. + +Legacy wrappers read the registry on each call. They use the new bridge after the reloader publishes it. + +A failed reload keeps the current bridge. A bound handle for that bridge remains usable. + +## Prototype evidence + +- Generate one module with a function, an overload, a generic, and a supported class or static method. +- Run two clients against distinct Python environments for the same generated module. Check interleaved and concurrent calls. +- Check that bound calls do not write the registry. Check that legacy imports still use the registry. +- Check argument, conversion, and return validation through both entrypoints. +- Check client disposal, shared borrowing, bridge disposal, failed calls, and reload behavior. +- Test Node and another bridge type where the test environment supports both. +- Compare emitted bytes for the original and revised generator on a small and a representative module. + +The Python fixture exports `create_client`, `dispose`, `identity`, `select`, `scale`, and `Client.label`. It checks names and signatures together. + +Two fixture directories provide the same Python module name and signature set. Each returns a different environment label. + +| Check | Expected result | +| --- | --- | +| Bind A and B with no global bridge | `a.api.environment()` returns `A`; `b.api.environment()` returns `B`; `getRuntimeBridge()` still throws. | +| Interleave and use `Promise.all` | Every call returns the label from its own Python directory. | +| Call Python collision names | `a.api.createClient()` and `a.api.dispose()` call Python; `a.api.Client.label('x')` returns `A:x`. | +| Check generated types | `identity('x')` accepts a string and returns `Promise`; `select` keeps correlated number and string branches; both `scale` call forms compile. | +| Trigger an argument or Python failure on A | A rejects; B still resolves; neither handle closes. | +| Call `invalidReturn()` on A | A rejects with `BridgeValidationError`; B still resolves. | +| Borrow one bridge in two handles | Disposing one handle leaves the other usable and does not dispose the bridge. | +| Dispose A twice | Both disposals succeed; later A calls reject with `BridgeDisposedError`; B stays usable. | +| Dispose the bridge owner | Later calls through its handle reject through the bridge's existing disposed behavior. | +| Reload successfully | The old bound handle keeps its old bridge; a new handle uses `reloader.current()`; legacy calls use the new global bridge. | +| Reload fails | The existing bound handle and global bridge keep the previous bridge. | + +The mixed-runtime check pairs `NodeBridge` with an HTTP test backend. Both use the same generated companion. + +The size report records raw UTF-8 bytes for legacy and opt-in source files, plus their generated declarations. + +Use `binding_fixture` for the small case and `test/fixtures/python/advanced_types.py` for the larger case. + +For each case, record `legacy.ts`, `legacy.d.ts`, `opt-in.ts total`, and `opt-in.d.ts total` in bytes. + +Compute source delta as `opt-in.ts total - legacy.ts`. Divide that delta by the number of generated callables. + +The opt-in prototype at `65bed95` passed all 22 jobs in [CI run 35503626271](https://github.com/bbopen/tywrap/actions/runs/35503626271). The Node 22 and Python 3.11 test job measured these raw UTF-8 bytes: + +| Module | Calls | Legacy `.ts` | Opt-in `.ts` total | Source increase | Legacy `.d.ts` | Opt-in `.d.ts` total | Declaration increase | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `binding_fixture` | 12 | 7,300 | 10,113 | 2,813 (38.5%) | 1,897 | 5,023 | 3,126 (164.8%) | +| `advanced_types` | 19 | 22,779 | 28,918 | 6,139 (27.0%) | 11,236 | 24,377 | 13,141 (117.0%) | + +The opt-in files add about 234 and 323 source bytes per callable, respectively. The declaration total more than doubles because it retains the legacy declarations and adds core and client declarations. This cost would apply when a future caller requests the three-file form. Production integration needs a package-size and editor-load budget. It can then decide whether to share more declarations before making the option public. The prototype has no public generation flag, so these measurements do not change default output. + +This design excludes transport pooling, Python object handles, and coroutine scheduling. diff --git a/docs/maintainers/client-binding-prototype-review.md b/docs/maintainers/client-binding-prototype-review.md new file mode 100644 index 00000000..2bb5494d --- /dev/null +++ b/docs/maintainers/client-binding-prototype-review.md @@ -0,0 +1,27 @@ +# Explicit client binding prototype review + +Reviewed code: draft [PR #355](https://github.com/bbopen/tywrap/pull/355) at `65bed9577254e68566827496a9693223da1e3e05`. Its base is the accepted callable compiler commit `42feeca0abd1314592be691faa6d608541dfc6d2`. + +## Result + +Accept the corrected internal prototype for this bounded review. It supports a shared callable core, a registry-backed legacy adapter, and a bound client companion. This verdict does not close issue #340 or approve a public generation option. + +A fresh independent review found a provenance defect in the earlier head `1e6ff97`: the renderer accepted a separately supplied template, which could route generated calls to another module. A bounded reproduction confirmed that mismatch. At `65bed95`, the renderer generates both forms from one compiled `PythonModule` and one `CodeGenerator`. The reviewer rechecked the corrected code and found no remaining runtime or type fidelity defect in this prototype. + +[CI run 35503626271](https://github.com/bbopen/tywrap/actions/runs/35503626271) passed all 22 jobs at the reviewed head. Its Node 22 and Python 3.11 job passed all 10 prototype tests. The matrix also passed Python 3.10 and 3.12, Bun, macOS, and Windows jobs. Local native tests were deferred because macOS memory pressure was level 2. Bounded local TypeScript parser checks and the independent source review supplemented CI. + +## API and ownership + +`bindRuntime(runtime)` returns `{ api, dispose }`. `BoundRuntime` requires only the bridge's `call` method. Calls in `api` capture that runtime. The handle borrows it: `dispose()` blocks later calls but never disposes the bridge or changes the registry. A call already started keeps its selected bridge. A second handle can borrow the same bridge. + +Python function names stay inside `api`, so `api.dispose()` remains a Python call. Supported class and static methods appear in plain namespaces. The legacy adapter still reads the registry on each call. After a successful reload, an old bound handle keeps its old bridge and a new handle can bind the replacement. A failed reload leaves the current bridge usable. + +The tests ran two clients against different Python directories with the same module name. They checked concurrent and interleaved calls, argument and return contracts, bytes, failures, class methods, shared borrowing, disposal, Node and HTTP bridges, reloads, an allocated runtime getter name, and rejection of source maps. A consumer typecheck covered generics and overloads. Python 3.10 checks the documented union fallback because its IR extractor cannot capture `@overload` signatures. The unresolved `TypeVar` output remains `Promise` in both generated forms. + +## Generated size + +The [design record](client-binding-design.md) gives raw source and declaration bytes from the final CI run. On Node 22 and Python 3.11, source text grew by 38.5% for `binding_fixture` and 27.0% for `advanced_types`. Declaration text grew by 164.8% and 117.0%. The extra declarations retain the legacy API and describe the core and client APIs. This is a material package and editor cost for a future public option. Production integration needs a size budget and may share more declarations. + +## Scope boundary + +PR #355 is a draft prototype. It does not add a public `generate()` option or package export. It does not wire output paths, collision checks, optional declaration output, source maps, or configured output formats into production emission. The renderer rejects generated source maps. A future `generate()` option must also reject `output.sourceMap` before invoking this renderer until all emitted files can carry maps. The default `generate()` path remains unchanged by this PR. diff --git a/docs/maintainers/coroutines.md b/docs/maintainers/coroutines.md new file mode 100644 index 00000000..80b801e1 --- /dev/null +++ b/docs/maintainers/coroutines.md @@ -0,0 +1,55 @@ +# Coroutine calls + +A `call` request returns one result or one error envelope. The bridge awaits a +Python awaitable before it serializes the result. It rejects generators and +async generators. It does not expose tasks, streams, retries, or cached results. + +## Node subprocess + +The Python JSONL server handles requests in order. A synchronous call runs +directly. For an awaitable result, `handle_call()` wraps it in a coroutine and +uses `asyncio.run()`. Python 3.10 through 3.12 create and close one event loop +for that call. Pending background tasks do not survive the call. + +The call must return an awaitable that can run on this new loop. A Future bound +to another loop fails in the normal Python error envelope. A synchronous +function that needs a running loop before it returns must create that loop +itself or use an `async def` function. + +After a request reaches stdin, a timeout or abort retires that Python process. +The transport rejects other requests on the same process and starts a new +process for later calls. Replacement runs the configured worker warmup. Python +state held only in the retired process is lost. A request that times out before +its first write does not retire the process. + +Retirement sends SIGTERM first. If the child stays alive, it sends SIGKILL after +one second and waits for the child to exit. A failed kill blocks replacement of +that process generation. The pool keeps the worker slot until disposal succeeds. +If cleanup fails, the pool rejects new leases and keeps the child handle for a +later disposal retry. + +Disposal kills the process and rejects pending requests. The caller receives one +timeout, abort, or disposal error. A retired process cannot send a late response +into a replacement process. A timeout does not cancel Python code in place; +process retirement stops code that does not cooperate with cancellation. + +## Pyodide + +Pyodide owns its +[WebLoop](https://pyodide.org/en/0.28.1/usage/api/python-api/webloop.html). The +bootstrap registers a task by request ID before it returns the task to +JavaScript. The transport awaits the task and destroys its Pyodide proxies after +the task settles. Timeout, abort, and disposal call `Task.cancel()` for that +request. The task map removes settled and cancelled tasks. + +Cancellation is cooperative. Python receives `CancelledError` at an await. The +caller receives one timeout, abort, or disposal error. The transport consumes a +late task rejection without sending another response. + +CPU-bound Python on the browser thread can block both the JavaScript timer and +the Pyodide event loop. This transport cannot stop it at a deadline. Pyodide +documents +[interrupt buffers](https://pyodide.org/en/0.28.1/usage/api/js-api.html#pyodide.setInterruptBuffer) +for web workers. The bridge does not install an interrupt buffer or terminate a +worker. Host applications must manage their own worker lifecycle if they need +that limit. diff --git a/docs/maintainers/value-contract-fixtures.v2.json b/docs/maintainers/value-contract-fixtures.v2.json new file mode 100644 index 00000000..78337545 --- /dev/null +++ b/docs/maintainers/value-contract-fixtures.v2.json @@ -0,0 +1,63 @@ +{ + "revision": 2, + "integerCases": [ + { "decimal": "-9007199254740991", "outcome": "number" }, + { "decimal": "9007199254740991", "outcome": "number" }, + { "decimal": "-9007199254740992", "outcome": "reject" }, + { "decimal": "9007199254740992", "outcome": "reject" }, + { "decimal": "9007199254740993", "outcome": "reject" }, + { "decimal": "-9223372036854775808", "outcome": "reject" }, + { "decimal": "9223372036854775807", "outcome": "reject" }, + { "decimal": "265252859812191058636308480000000", "outcome": "reject" } + ], + "bytesCases": [ + { + "logicalHex": "00ff80", + "requestEnvelope": { "__tywrap_bytes__": true, "b64": "AP+A" }, + "responseEnvelope": { "__type__": "bytes", "encoding": "base64", "data": "AP+A" }, + "decodedAs": "Uint8Array[0,255,128]" + }, + { + "logicalHex": "", + "requestEnvelope": { "__tywrap_bytes__": true, "b64": "" }, + "responseEnvelope": { "__type__": "bytes", "encoding": "base64", "data": "" }, + "decodedAs": "Uint8Array[]" + } + ], + "binary16Cases": [ + { "wordHex": "0000", "outcome": "0" }, + { "wordHex": "8000", "outcome": "-0" }, + { "wordHex": "0001", "outcome": "5.960464477539063e-8" }, + { "wordHex": "03ff", "outcome": "0.00006097555160522461" }, + { "wordHex": "0400", "outcome": "0.00006103515625" }, + { "wordHex": "3e00", "outcome": "1.5" }, + { "wordHex": "c080", "outcome": "-2.25" }, + { "wordHex": "7bff", "outcome": "65504" }, + { "wordHex": "fbff", "outcome": "-65504" }, + { "wordHex": "7c00", "outcome": "reject" }, + { "wordHex": "fc00", "outcome": "reject" }, + { "wordHex": "7e00", "outcome": "reject" } + ], + "compositionCases": [ + { + "path": "result.outer[0].value", + "logicalValue": "9007199254740993", + "outcome": "reject" + }, + { + "path": "result.outer[0].tensor.value", + "logicalValue": "float16[1.5,-2.25]", + "outcome": "number[1.5,-2.25]" + } + ], + "unionCases": [ + { "contract": "str|int", "value": "label", "outcome": "string" }, + { "contract": "str|int", "value": 42, "outcome": "safe-integer number" }, + { "contract": "str|int", "value": 9007199254740992, "outcome": "reject" } + ], + "tupleCases": [ + { "contract": "tuple[str,int]", "value": ["label", 42], "outcome": "accept" }, + { "contract": "tuple[str,int]", "value": ["label"], "outcome": "reject-length" }, + { "contract": "tuple[str,int]", "value": ["label", 9007199254740992], "outcome": "reject-integer" } + ] +} diff --git a/docs/maintainers/value-contract-fixtures.v3.json b/docs/maintainers/value-contract-fixtures.v3.json new file mode 100644 index 00000000..f5d419af --- /dev/null +++ b/docs/maintainers/value-contract-fixtures.v3.json @@ -0,0 +1,36 @@ +{ + "revision": 3, + "integerCases": [ + { + "logicalDecimal": "0", + "envelope": { "__tywrap__": "integer", "codecVersion": 2, "encoding": "decimal", "value": "0" } + }, + { + "logicalDecimal": "9007199254740991", + "envelope": { "__tywrap__": "integer", "codecVersion": 2, "encoding": "decimal", "value": "9007199254740991" } + }, + { + "logicalDecimal": "18446744073709551617", + "envelope": { "__tywrap__": "integer", "codecVersion": 2, "encoding": "decimal", "value": "18446744073709551617" } + }, + { + "logicalDecimal": "-18446744073709551617", + "envelope": { + "__tywrap__": "integer", + "codecVersion": 2, + "encoding": "decimal", + "value": "-18446744073709551617" + } + } + ], + "rejectedDecimals": ["-0", "+1", "01", "1.0", "1e3", "١", ""], + "floatNegativeZero": { + "envelope": { "__tywrap__": "float", "codecVersion": 2, "encoding": "negative-zero" }, + "decodedAs": "negative zero" + }, + "migration": { + "default": "Python int remains a safe JavaScript number under revision 2", + "opted": "Python int becomes bigint at every declared integer node under revision 3", + "caller": "bigint arithmetic and JSON persistence require explicit handling" + } +} diff --git a/docs/maintainers/value-contract-prototypes.md b/docs/maintainers/value-contract-prototypes.md new file mode 100644 index 00000000..49ba6be9 --- /dev/null +++ b/docs/maintainers/value-contract-prototypes.md @@ -0,0 +1,147 @@ +# Value extension prototypes + +These rules are candidates for #337 and #339. They do not change the 0.11 codec +policy. The prototypes live under `test/prototypes`. Shipped wrappers cannot +import them. + +## Exact integer option + +The proposed public option is `integerMode: 'bigint'` for one callable. It would +map every Python `int` parameter and result to TypeScript `bigint`. Safe +integers use the same type. Python `bool` remains `boolean`. Calls without the +option keep the safe `number` rule. + +The default value-contract revision 2 represents Python `int` as a safe JSON +`number`. The bounded revision 3 proof selects +`EXACT_INTEGER_VALUE_CONVERSION` for an analyzed Python module. It emits +`bigint` wrappers and validators for scalar and nested results through a +test-only runtime binding. A public per-callable option and production bridge +adapter are not implemented. + +The proposed generated wrapper must require `exactIntegerDecimalV2` in the +bridge's `meta.valueCapabilities`. It must send +`params.valuePolicy.integer = 'bigint-v2'` on each call. A new bridge must +reject unknown policies. An old bridge lacks the capability, so the wrapper must +reject the call before sending a tag. The bound proof checks the capability +before its private adapter encodes arguments. That adapter sends the policy to +the Python prototype. The default bridge does not implement this mode. + +The version 2 integer envelope is +`{"__tywrap__":"integer","codecVersion":2,"encoding":"decimal","value":"18446744073709551617"}`. +`codecVersion` uses the parsed JSON numeric value. The lexemes `2`, `2.0`, and +`2e0` all mean version 2. Booleans and strings do not. The decimal must match +`^(?:0|[1-9][0-9]*|-[1-9][0-9]*)$`. This excludes `-0`, leading zeros, plus +signs, spaces, exponents, and Unicode digits. The value permits at most 4096 +digits, excluding the sign. It uses at most 4097 ASCII bytes. Whole request and +response byte limits still apply. + +The TypeScript encoder tags every `bigint`, including safe values. The Python +request decoder requires the tag at each declared integer node. It rejects raw +JSON numbers there. It uses the trusted resolved value contract to distinguish +integer nodes from float nodes. A generated wrapper must not let a client supply +or change that contract. + +`JSON.stringify(1.0)` emits `1`. The Python decoder converts that token to +`float` only at a declared float node. `JSON.stringify(-0)` emits `0`, so the +TypeScript encoder uses +`{"__tywrap__":"float","codecVersion":2,"encoding":"negative-zero"}` for +negative zero. The Python decoder accepts that tag only at a float node. It +rejects malformed float tags and nonfinite numbers. + +The Python response encoder tags every `int`, including safe values. The +TypeScript response decoder returns `bigint` at declared integer nodes. The +generated revision 3 return validator requires `bigint`. The prototype decoder +rejects an ordinary number and a raw tag. Arrow int64 keeps its current Arrow +encoding and decoded type. + +Both prototypes walk nested arrays and string-keyed records within depth and +node limits. They reject unsupported values and malformed envelopes. Encoders +reject cycles with paths. Ordinary records cannot use `__tywrap__` as a key +because the decoder reserves it for envelopes. + +The prototype counts UTF-8 bytes of compact JSON. Python emits Unicode +characters directly, as `JSON.stringify` does. Both paths reject unpaired +surrogates. Production must check raw wire bytes before parsing; object-level +checks do not prove equal byte counts for alternate numeric JSON spellings. + +The bounded tests round trip positive and negative values beyond 64 bits. They +cover floats, booleans, nested records, malformed tags, digit limits, byte +limits, and old bridges. `test/value_extensions_generated_integer.test.ts` uses +analyzer IR to check `bigint` and `bigint[]` inputs, `Promise` and +`Promise` outputs, and generated bigint return validation at a +nested index. It checks signed zero, a client request limit before dispatch, +the Python raw input limit, and that an incapable bridge receives no exact +request. The same fixture under revision 2 keeps `number` types and uses an +ordinary call. Production still needs a public opt-in selector, bridge +capability negotiation, and application migration measurements. + +### Exact integer migration cost + +Opting in changes every declared Python `int` at that callable to TypeScript +`bigint`, including values within the safe number range. Callers must update +number arithmetic, comparisons, and stored JSON. `JSON.stringify` rejects a +plain `bigint`, so callers that persist results need an explicit encoding. + +Each tagged integer adds 73 JSON bytes beyond its decimal digits. For example, +`7` uses one byte as a JSON number and 74 bytes in the version 2 envelope. +Nested collections multiply that cost by their integer count. Teams must measure +representative call payloads against the byte limit before enabling the option. + +For a compact `{"args": [...]}` payload with three integers, a boolean, and a +float, the safe-value example grows from 28 to 247 UTF-8 bytes (8.82 times). +Using one 81-bit and one 131-bit integer grows the same shape from 91 to 310 +bytes (3.41 times). These figures exclude the surrounding RPC envelope and do +not estimate application traffic. + +The client must check the bridge capability before it sends tagged values. This +requires a coordinated client and bridge rollout. Old bridges reject the opted +call. Arrow int64 columns keep their current type and wire format. + +Before production adoption, inventory generated call sites that use `int`, +measure payload growth, and typecheck downstream callers after the opt-in. The +prototype has not measured those application-specific costs. + +## Dataclass output option + +The generation option is `dataclassReturns: 'validated-v2'` for a callable with +an annotated dataclass result. Dataclass inputs remain unsupported. Ordinary +class instances do not qualify. + +The generator compiles `dataclasses.fields` into a structural TypeScript record. +It includes fields with defaults and `init=False`. An instance returns those +fields. `Optional[T]` permits `null`; a default does not make a returned +property optional. + +The proposed generated wrapper must require `dataclassFieldsV2` in +`meta.valueCapabilities`. It must send +`params.valuePolicy.dataclass = 'fields-v2'` on each call. The Python prototype +encoder accepts only the declared dataclass type. It emits a version 2 envelope +with `module.qualname` identity and an ordered `fields` record. It rejects +unsupported fields and cycles with paths. It applies depth, node, and byte +limits. It does not call `dataclasses.asdict` or create object handles. + +The TypeScript prototype decoder checks marker, version, encoding, type +identity, and exact fields before it removes the envelope. It returns a plain +record. A module-private `WeakMap` stores verified type identity. The prototype +origin check reads that entry. A plain record cannot claim dataclass origin. A +nested dataclass gets its own entry. The current generated return validator +checks required field types but does not check origin or reject extra keys. The +adapter must perform those checks before it calls the validator. + +The Python prototype checks the declared root dataclass type. It serializes +nested dataclasses by their observed runtime type and does not check a compiled +field contract. The TypeScript decoder rejects unexpected nested identities or +field values. Server-side field validation remains open. + +The bounded Point proof in `test/value_extensions_generated_point.test.ts` uses +analyzer IR from an importable Python module. The compiler emits +`Promise` with required numeric `x` and `y`, including a defaulted `y`. A +bound prototype adapter returns `{x: 1, y: 2}` and rejects missing, extra, wrong +typed fields, and untagged records before the generated validator runs. The +generated validator independently rejects wrong field types. The binding rejects +a bridge without the Point policy adapter. + +The Python prototype tests optional fields, nesting, cycles, unsupported fields, +depth, and byte limits separately. Production still needs bridge capability +negotiation, a server-side compiled field contract, and an independent design +review. The default runtime has no dataclass adapter. diff --git a/docs/maintainers/value-contracts.md b/docs/maintainers/value-contracts.md new file mode 100644 index 00000000..b0e4481d --- /dev/null +++ b/docs/maintainers/value-contracts.md @@ -0,0 +1,113 @@ +# Value contracts + +The frozen internal prototype is +[value-contracts.v2.json](value-contracts.v2.json). That JSON file owns the +policy. The TypeScript interface mirrors it and has revision 2. + +Each contract names a logical value, its wire encoding, its decoded JavaScript +value, and its constraints. Sequences, fixed tuples, records, and unions compose +child contracts. A union has two to 32 alternatives. The compiler rejects a +union if one wire value could decode two ways. Contract depth stops at 64. Named +records can inline within that limit. Recursive aliases stay unsupported until a +reviewed reference graph exists. The prototype covers float16 ndarrays and Torch +tensors. Other Arrow types keep their existing rules. In particular, Arrow int64 +may decode as `bigint`. Unsupported conversions carry a reason and guidance. + +The wire stays at `tywrap/1` and scientific `codecVersion: 1`. Existing Arrow +envelopes, JSON fallback, and transports keep their shape. The producer rejects +unsafe Python integers before it writes JSON. A generated wrapper that consumes +this interface must keep `number` for Python `int` and add a safe-integer return +constraint. Regenerate wrappers after that compiler change. Do not return +`bigint` under an existing `Promise`. + +The bytes leaf keeps the existing base64 envelopes. Requests use +`__tywrap_bytes__`; responses use `__type__: bytes`. Both decode to +`Uint8Array`. The Torch float16 contract names `torch.float16` on the outer +tensor and `float16` on its nested version 1 ndarray. The decoder rejects a +different nested dtype before it decodes the data. + +Migration for users with large Python integers: convert them to strings in +Python with an explicit return annotation, or keep integer columns in Arrow +tables. JSON fallback for ndarray and pandas values still rejects unsafe +integers. This is a behavior change from silent rounding to a call error. + +The [fixed proof fixtures](value-contract-fixtures.v2.json) cover integer +boundaries, binary16 values, unions, fixed tuples, and nested paths. The focused +tests also compare every finite binary16 storage word with an independent +float32 bit reference. They test signed zero with `Object.is`. + +The Python serializer checks plain integers, NumPy scalar integers, and model +dumps during its existing value walk. It also checks terminal estimator +parameters and Series name metadata before JSON output. A JSON ndarray or sparse +matrix checks integer data before it creates an envelope. Sparse metadata checks +shapes and indices. The TypeScript decoder converts float16 Arrow storage during +extraction, before it reshapes the ndarray. Torch uses that same ndarray path. +These checks do not walk Arrow payloads again for schema validation. + +## Exact bigint extension for #337 + +The [revision-3 policy](value-contracts.v3.json) is a bounded prototype. It pins +the revision-2 policy and adds one `integer-exact` leaf. Revision 2 remains the +default safe-number policy. No default bridge supports bigint calls yet. + +The internal `EXACT_INTEGER_VALUE_CONVERSION` selects revision 3 for a fixture +module. It maps Python `int` to TypeScript `bigint` in parameters and returns. +The generated validator requires `bigint` at nested integer nodes. Python `bool` +and finite `float` keep their revision-2 rules. The compiler requires an +explicit `exact-integer-adapter` capability. It is unavailable by default. The +prototype has no public per-callable option for mixed modules. + +The opted call uses a version-2 integer envelope with a canonical signed decimal +string. A sample value is +`{"__tywrap__":"integer","codecVersion":2,"encoding":"decimal","value":"18446744073709551617"}`. +The companion test adapter must check the grammar and 4096-digit limit in both +directions. It must use `BigInt` only after validation. Arrow int64 keeps its +current path. Contract revision 3, envelope `codecVersion: 2`, per-call policy +`bigint-v2`, and RPC protocol `tywrap/1` are different version labels. + +The bound test provider must see `exactIntegerDecimalV2` in bridge metadata +before it sends a tagged request. It sets `params.valuePolicy.integer` to +`bigint-v2`. Calls without that policy keep revision-2 behavior. The production +bridge does not negotiate this capability. Unknown versions and malformed +decimal values must fail with a path. + +The [revision-3 fixtures](value-contract-fixtures.v3.json) record exact values, +negative zero, and migration cost. The generated proof still needs integrated CI +and independent review before #337 can close. A prototype does not enable bigint +by default or authorize a release. + +## Dataclass return extension for #339 + +This extension is a design sketch. Dataclass inputs remain unsupported and need +a separate input contract. Users must pass a plain record through an explicitly +typed function if they need that behavior now. + +For an annotated dataclass return, compile a structural TypeScript record from +`dataclasses.fields`. Include each instance field in the output, including +fields with defaults or `init=False`. A default does not make a returned field +optional. A field annotated `Optional[T]` permits `null`. Compose nested +dataclasses, records, and sequences only when every field has a supported value +contract. Reject ordinary class instances and unsupported fields with their +result paths. + +Use a version 2 dataclass envelope with a declared type identity and a `fields` +record. For example, `Point(1, 2)` would carry +`{"__tywrap__":"dataclass","codecVersion":2,"encoding":"fields","type":"fixtures.values_torture.Point","fields":{"x":1,"y":2}}`. +The TypeScript decoder returns `{x: 1, y: 2}`. The generated validator must +check the type identity, exact field names, field values, and required fields. +It must reject extra fields unless the compiled contract allows them. The Python +encoder must use the current bounded value walk. It must detect cycles and +enforce depth, node, and payload limits without calling `dataclasses.asdict` as +a shortcut. + +The bridge must advertise dataclass value support. A generated dataclass wrapper +must reject an older bridge before calling it. A new bridge must send the +envelope only when the wrapper requests it. This leaves existing value RPC and +ordinary class behavior unchanged. + +Acceptance evidence still needed: a generated `Promise` wrapper must +return the exact plain record and reject missing, extra, or wrong typed fields. +Tests must cover optional and defaulted fields, nested values, cycles, +unsupported fields, depth, and payload limits. An independent review must +approve the type identity, version rule, and migration cost before #339 can +close. diff --git a/docs/maintainers/value-contracts.v2.json b/docs/maintainers/value-contracts.v2.json new file mode 100644 index 00000000..827a766c --- /dev/null +++ b/docs/maintainers/value-contracts.v2.json @@ -0,0 +1,85 @@ +{ + "revision": 2, + "status": "frozen-internal-prototype", + "transport": "tywrap/1 value RPC", + "codecVersion": 1, + "rules": { + "integer": { + "logicalKind": "Python int, excluding bool", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "wire": "JSON integer number", + "decodedAs": "JavaScript number", + "failure": "reject before JSON encoding with result path and explicit conversion guidance" + }, + "float": { + "logicalKind": "finite Python float", + "constraint": "finite", + "wire": "JSON number", + "decodedAs": "JavaScript number", + "failure": "reject NaN and Infinity" + }, + "bytes": { + "logicalKind": "Python bytes or bytearray", + "requestWire": "existing __tywrap_bytes__ base64 envelope", + "responseWire": "existing __type__: bytes base64 envelope", + "decodedAs": "JavaScript Uint8Array", + "failure": "reject malformed base64 or payloads above the existing byte limit" + }, + "sequence": { + "logicalKind": "list or variadic tuple of one contracted item kind", + "wire": "JSON array", + "decodedAs": "JavaScript array", + "composition": "apply each item rule at its result path" + }, + "tuple": { + "logicalKind": "fixed-length heterogeneous tuple of contracted values", + "wire": "JSON array", + "decodedAs": "JavaScript array with one contracted value per position", + "composition": "require exact length and apply each item rule at its result index; an empty tuple is valid" + }, + "union": { + "logicalKind": "one value matching a nonempty set of contracted alternatives", + "wire": "the selected alternative's existing wire encoding", + "decodedAs": "the selected alternative's JavaScript value", + "minimumAlternatives": 2, + "maximumAlternatives": 32, + "composition": "require at least one matching alternative; reject a contract if the same wire value can match alternatives with different decoded representations; order has no semantic effect", + "failure": "reject an empty or one-option union during contract construction; reject a value that matches no alternative with its path" + }, + "record": { + "logicalKind": "string-keyed record of contracted values", + "wire": "JSON object", + "decodedAs": "JavaScript object", + "composition": "apply each field rule at its result path" + }, + "ndarray-float16": { + "logicalKind": "NumPy float16 ndarray", + "wire": "codecVersion 1 ndarray Arrow envelope; JSON fallback stays explicit", + "decodedAs": "JavaScript numeric scalar or nested array", + "conversion": "decode each Arrow Uint16 storage word as IEEE 754 binary16 before reshape", + "failure": "reject non-finite converted values" + }, + "torch-float16": { + "logicalKind": "Torch float16 tensor", + "wire": "codecVersion 1 torch.tensor envelope containing ndarray envelope", + "decodedAs": "tensor record with numeric data", + "outerDtype": "torch.float16", + "nestedDtype": "float16", + "conversion": "reuse ndarray-float16 rule for nested value" + } + }, + "prototypeBoundary": "Only float16 scientific values use the new ndarray contract. Existing Arrow int64 values may decode as bigint and keep their current rules.", + "contractLimits": { + "maximumDepth": 64, + "maximumUnionAlternatives": 32, + "namedRecordAliases": "inline nonrecursive aliases within the depth limit", + "recursiveAliases": "unsupported until a reviewed reference-graph contract exists" + }, + "compatibility": { + "wireChange": false, + "unknownVersion": "reject", + "unsafeInteger": "previous clients could round; new producers reject", + "generatedWrappers": "regenerate when callable-contract code consumes revision 2" + } +} diff --git a/docs/maintainers/value-contracts.v3.json b/docs/maintainers/value-contracts.v3.json new file mode 100644 index 00000000..e7b5c0ae --- /dev/null +++ b/docs/maintainers/value-contracts.v3.json @@ -0,0 +1,51 @@ +{ + "revision": 3, + "status": "bounded-internal-prototype", + "base": { + "file": "value-contracts.v2.json", + "revision": 2, + "hashCanonicalization": "UTF-8 with LF line endings", + "sha256": "554f84b75126513250a7eb773294347fe4dc42262e4ac52f86e7aa19cc65bb4e" + }, + "transport": "tywrap/1 value RPC", + "exactIntegerEnvelopeCodecVersion": 2, + "callPolicy": "bigint-v2", + "requiredCapability": "exactIntegerDecimalV2", + "rules": { + "integer-exact": { + "logicalKind": "Python int, excluding bool, on an opted call", + "contract": { + "kind": "integer-exact", + "wire": "decimal-string-envelope", + "decodedAs": "bigint", + "constraint": "exact-integer" + }, + "wire": { + "__tywrap__": "integer", + "codecVersion": 2, + "encoding": "decimal", + "value": "canonical signed decimal string" + }, + "decimalGrammar": "^(?:0|[1-9][0-9]*|-[1-9][0-9]*)$", + "maximumDigitsWithoutSign": 4096, + "composition": "apply the exact integer rule at every selected sequence, tuple, union, and record node" + }, + "float-negative-zero": { + "logicalKind": "Python float equal to negative zero on an opted call", + "wire": { + "__tywrap__": "float", + "codecVersion": 2, + "encoding": "negative-zero" + }, + "decodedAs": "JavaScript negative zero", + "otherFiniteFloats": "JSON number under the inherited finite float rule" + } + }, + "compatibility": { + "revision2Default": "unchanged safe-number integer rule", + "unknownRevision": "reject", + "missingCapability": "reject before sending a tagged request", + "oldClientNewProvider": "revision 2 behavior unless the call opts in", + "arrowInt64": "keep the existing Arrow rule" + } +} diff --git a/docs/public/llms-full.txt b/docs/public/llms-full.txt index 47a36b49..ad186c8f 100644 --- a/docs/public/llms-full.txt +++ b/docs/public/llms-full.txt @@ -9,7 +9,10 @@ layout: home --- -## Quick Start +## Try it + +Install the TypeScript package and Python generator. Then create a config and +generate wrappers for the Python modules you want to call. ```bash npm install tywrap @@ -27,33 +30,14 @@ import { setRuntimeBridge } from 'tywrap/runtime'; import * as math from './generated/math.generated.js'; setRuntimeBridge(new NodeBridge({ pythonPath: 'python3' })); -const result = await math.sqrt(16); // 4, typed from the Python annotation -``` - -## Development Hot Reload - -```typescript -import { startNodeWatchSession } from 'tywrap/dev'; -import { NodeBridge } from 'tywrap/node'; - -const session = await startNodeWatchSession({ - configFile: './tywrap.config.ts', - createBridge: async config => - new NodeBridge({ - pythonPath: config.runtime.node?.pythonPath ?? 'python3', - timeoutMs: config.runtime.node?.timeout ?? 30000, - }), -}); +const result = await math.sqrt(16); // 4 ``` -Use `reloadNow()` for an explicit rebuild or `close()` to stop watching. Node -gets full hot reload, Pyodide gets manual bridge replacement through -`createBridgeReloader(...)`, and HTTP reload remains external to tywrap. +See the [getting started guide](https://bbopen.github.io/tywrap/guide/getting-started) to configure your own +Python module and choose a runtime bridge. > Experimental: APIs may change before v1.0.0. See [Releases](https://github.com/bbopen/tywrap/releases) for breaking changes. -> If tywrap saves you time, a ⭐ on [GitHub](https://github.com/bbopen/tywrap) helps others find it. - --- @@ -380,7 +364,7 @@ and `tywrap:check` scripts to `package.json` (disable with `--no-scripts`). 1. Set `"caching": true` to reuse generation IR across rebuilds. 2. Limit `functions` and `classes` when a wrapper needs only part of a module. -`batching` and `compression` are accepted config fields in 0.9.0, but no current +`batching` and `compression` are accepted config fields in 0.10.0, but no current generator or runtime code applies them. ```json @@ -457,6 +441,142 @@ const [sinValue, cosValue, tanValue] = await Promise.all([ --- + +# Migrating to 0.11 + +This guide covers the planned 0.11 changes. The release is not published yet. + +## Large Python integers + +Python `int` results still use TypeScript `number`. The supported range is +`-9007199254740991` through `9007199254740991`, inclusive. + +Earlier versions could round larger integers when JavaScript parsed the response. +The new serializer rejects those values before writing JSON. This applies to root +results, nested containers, supported NumPy scalars, and model dumps. + +For example, a result containing `{"items": [9007199254740993]}` now fails at +`result.items[0]`. The error identifies the unsafe value and suggests an explicit +string or an Arrow integer column. + +Return a string when the value represents an identifier or must remain an exact +decimal integer: + +```python +def large_identifier() -> str: + return str(9007199254740993) +``` + +The generated return type is `Promise`. Convert that string with +JavaScript `BigInt` if your application needs integer arithmetic. Validate any +string that comes from an untrusted source before using it. + +Keep integer columns in Arrow tables when you need the existing Arrow int64 +representation. Arrow int64 remains exact and can decode as JavaScript `bigint`. +JSON fallback does not provide that representation and rejects unsafe integers. + +Booleans and finite floats remain supported. Converting an integer to a Python +`float` can lose precision before tywrap receives it. Use a string when exactness +matters. Tagged bigint transport remains a separate design proposal. + +## NumPy and Torch float16 + +The Arrow decoder now converts float16 storage words into their numeric values +before reshaping the result. For example, `[15872, 49280]` becomes the intended +`[1.5, -2.25]`. Remove application code that manually decodes those storage words. + +The conversion preserves signed zero, finite subnormal values, and finite extrema. +NumPy arrays and nested Torch tensors use the same conversion. Non-finite results +continue to reject under the existing policy. + +The scientific envelope format, JSON fallback, and Arrow int64 behavior stay +compatible. Torch bfloat16 keeps its existing float32 transport conversion. + +## Return types that cannot be validated + +An unresolved Python `object` result now produces `Promise`. Python +objects can include strings and numbers, which TypeScript's `object` type excludes. + +An unresolved generic result also becomes `unknown`. Earlier wrappers could +declare `Promise` while accepting any returned value. A generic input remains +generic, but its type alone cannot prove that Python returned the same type. +This also applies when the unresolved type parameter appears in a nested result. + +Generation reports the unresolved conversion. `--fail-on-warn` rejects that +diagnostic. Use a supported concrete return annotation or overload when the +Python API has a known result type. Otherwise, check the value before using it: + +```ts +const result = await generatedFunction(input); +if (typeof result !== 'string') { + throw new TypeError('Expected a string result'); +} +console.log(result.toUpperCase()); +``` + +The current value contract does not resolve every Python annotation. For example, +`Literal` results become `unknown`, while their existing literal checks remain. +Other unresolved returns retain available marker, container or record checks. +These partial checks do not prove a precise TypeScript return type. +Type-only Protocol methods keep their declared generic signatures. + +Supported string and integer overloads retain their corresponding return types. +Use Python 3.11 or later to extract registered overloads. Python 3.10 keeps the +implementation signature when its typing module cannot expose the overloads. + +## Coroutine results + +The updated Node and Pyodide bridges await Python coroutine results. Generated +wrappers use the function's resolved result type, such as `Promise`. +Upgrade the generator and runtime together, then regenerate wrappers. + +An HTTP client still depends on its server. Use a compatible server that awaits +Python results; upgrading the TypeScript client does not update that server. + +## Regenerate wrappers + +After these versions are published, upgrade both packages: + +```bash +npm install tywrap@0.11.0 +python3 -m pip install --upgrade tywrap-ir==0.3.1 +``` + +Use the Python executable selected by `runtime.node.pythonPath` and +`runtime.node.virtualEnv` instead of `python3` when your configuration differs. +The new extractor captures generic parameters used only in overload annotations. +Its IR schema remains `0.4.0`, so the schema check alone cannot detect an older +extractor or an older saved contract. + +Extract fresh IR when regenerating: + +```bash +npx tywrap generate --no-cache +``` + +This bypasses the on-disk IR cache. It does not replace existing cache entries. +If you enable caching again, first remove the old generated IR files from +`.tywrap/cache` so generation extracts and caches the updated contracts. + +If you use `contractInput`, temporarily omit it to extract fresh contracts with +the updated Python package. Review each new `.contract.json` in your +output directory. Replace the corresponding pinned input file with that contract, +or point `contractInput` to the new file. Then restore the setting. +The `--no-cache` option does not replace a pinned input contract. + +Regenerate wrappers with the upgraded generator. Python `int` return validators +then check the safe integer range as well as the JavaScript value type. +Regeneration also applies the reviewed callable-contract diagnostics. + +Update any tests that expected a rounded integer or float16 storage words. +Assert the corrected value or the specific conversion error instead. + +Run your generated calls against the upgraded runtime before deploying them. +An old wrapper cannot add the new generated return checks by itself, although the +upgraded Python serializer still rejects unsafe integer results. + +--- + # Agent Adoption @@ -773,7 +893,7 @@ types: { ``` Accepted presets are `numpy`, `pandas`, `pydantic`, `stdlib`, `scipy`, `torch`, -and `sklearn`. `numpy` is accepted as a no-op in 0.9.0. The other presets map +and `sklearn`. `numpy` is accepted as a no-op in 0.10.0. The other presets map the library types implemented by the generator, such as `DataFrame`, sparse matrix classes, `Tensor`, and `BaseEstimator`. @@ -1721,7 +1841,7 @@ See the [Node.js troubleshooting guide](https://bbopen.github.io/tywrap/guide/ru --- -# Browser Runtime Guide +# Browser runtime guide Run Python in the browser using Pyodide WebAssembly. @@ -1732,14 +1852,16 @@ Run Python in the browser using Pyodide WebAssembly. - Pre-built packages via Pyodide - Works well for notebooks, demos, and client-side analysis -## Quick Start +## Quick start ### Install + ```bash npm install tywrap pyodide ``` ### Configure + ```json { "pythonModules": { @@ -1748,7 +1870,7 @@ npm install tywrap pyodide }, "runtime": { "pyodide": { - "indexURL": "https://cdn.jsdelivr.net/pyodide/v0.28.0/full/", + "indexURL": "https://cdn.jsdelivr.net/pyodide/v0.28.1/full/", "packages": ["numpy", "matplotlib", "scipy"] } } @@ -1756,14 +1878,15 @@ npm install tywrap pyodide ``` ### Use + ```ts import { PyodideBridge } from 'tywrap/pyodide'; import { setRuntimeBridge } from 'tywrap/runtime'; import { array } from './generated/numpy.generated.js'; const bridge = new PyodideBridge({ - indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.28.0/full/', - packages: ['numpy'] + indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.28.1/full/', + packages: ['numpy'], }); setRuntimeBridge(bridge); @@ -1772,7 +1895,7 @@ const arr = await array([1, 2, 3]); console.log(arr); ``` -## Configuration Options +## Configuration options ```ts interface PyodideBridgeOptions { @@ -1781,22 +1904,28 @@ interface PyodideBridgeOptions { } ``` -The `packages` array is loaded during initialization. For additional package +The bridge loads the `packages` array during initialization. For additional package loading, rely on Pyodide directly. -## Data Transport +## Data transport -Arrow envelopes are supported in the browser if you register an Arrow decoder (Node auto-registers when `apache-arrow` is installed): +PyodideBridge uses JSON transport. It converts supported NumPy arrays and pandas +tables to JSON envelopes. It does not send Arrow payloads. -```ts -import { registerArrowDecoder } from 'tywrap'; +See [codec envelopes](https://bbopen.github.io/tywrap/codec-envelopes.md) for supported values and transport limits. -registerArrowDecoder(bytes => bytes); -``` +## Build integration -## Build Integration +Run `tywrap generate` during your build. Load Pyodide at runtime from a CDN or your own server. -Run `tywrap generate` during your build and load Pyodide at runtime (CDN or self-hosted). +## Test coverage + +The unit tests mock the Pyodide loader. The cross-backend suite runs the shared +Python bootstrap under CPython. Neither check proves browser execution. + +Required CI also runs the pinned Pyodide package in Node WebAssembly and a +Chromium smoke test. The browser test loads local Pyodide assets and executes a +generated wrapper. --- @@ -1852,6 +1981,11 @@ setRuntimeBridge( payloads. You must provide a compatible server endpoint. Each call is an independent POST request because the protocol is stateless. +Generated async callables have typed results when their return annotations have +supported value conversions. The in-repo Node and Pyodide bridges await Python +coroutines. For `HttpBridge`, your server must await coroutines before it sends +the result. `HttpBridge` cannot verify a remote server's coroutine support. + tywrap does not include an HTTP server. See the [API reference](https://bbopen.github.io/tywrap/reference/api/) for the expected request and response format. @@ -2439,7 +2573,7 @@ Generates TypeScript shaped like: export type Pair = [T, T]; export type Transform

= (...args: P) => T; export class Container { - // NOTE: Instance members are not generated in v0.9; migrate this API to value-returning module functions. + // NOTE: Instance members are not generated in v0.10; migrate this API to value-returning module functions. } ``` @@ -2747,7 +2881,7 @@ so a payload can exceed the JSONL line ceiling. The capability is statically [Transport framing](https://bbopen.github.io/tywrap/transport-framing.md) for the wire format. `supportsStreaming` (incremental results for a single request) is `false` on -every backend. It is not implemented as of 0.9.0. +every backend. It is not implemented as of 0.10.0. ### `maxFrameBytes` @@ -2801,7 +2935,7 @@ through a `PooledTransport` lease reassembles correctly (see ## Scope: subprocess only -`tywrap-frame/1` is **subprocess-only** as of 0.9.0. The subprocess transport is +`tywrap-frame/1` is **subprocess-only** as of 0.10.0. The subprocess transport is the only backend with a real frame ceiling, the JSONL line-length limit. The other backends stay single-frame and keep `supportsChunking: false`: @@ -2811,7 +2945,7 @@ other backends stay single-frame and keep `supportsChunking: false`: - **Pyodide** is in-memory (`maxFrameBytes: Number.POSITIVE_INFINITY`, JSON-only). There is no wire to fragment. -`supportsStreaming` stays `false` on every backend as of 0.9.0. +`supportsStreaming` stays `false` on every backend as of 0.10.0. ## Layering @@ -2890,7 +3024,7 @@ construction. The codepoint-boundary rule is a sender obligation: a frame's `data` MUST NOT split a multi-byte UTF-8 sequence, so the receiver can decode each frame as valid UTF-8 and concatenate without re-aligning bytes across frame edges. `utf8-base64` remains a defined alternative in the wire schema for future -use (e.g. a non-text payload), but tywrap does not emit it as of 0.9.0. +use (e.g. a non-text payload), but tywrap does not emit it as of 0.10.0. > Implementation note for later workstreams: `total` and the per-frame split > points are computed over the message's UTF-8 **byte** length against @@ -3072,6 +3206,12 @@ When `output.declaration` is enabled, `generate()` writes matching code. Simple `TypeVar` and callable `ParamSpec` declarations are preserved when tywrap can represent them safely. +Unresolved return annotations now emit `Promise` and a located warning. +This includes `TypeVar` and `ParamSpec` results without a supported value +conversion. Input generics remain in the declaration. Earlier versions could +emit `Promise` without validating the decoded value as `T`; callers must +narrow the result or use a supported concrete overload. + `generate()` returns: ```ts @@ -3332,8 +3472,9 @@ the declared return schema. | Stage | Owners | Invariant | | --- | --- | --- | | Python analysis | `tywrap_ir/tywrap_ir/__main__.py`, `tywrap_ir/tywrap_ir/` | The extractor emits JSON typed IR for the requested module. | -| IR contract | `src/tywrap.ts`, `src/types/` | A contract has the expected module and `ir_version`. The current version is `0.4.0`. | -| Wrapper generation | `src/core/generator.ts`, `src/core/emit-call.ts`, `src/core/mapper.ts` | Generated calls carry a `ReturnSchema` that represents the Python return annotation. | +| IR contract | `src/core/ir-contract.ts`, `src/tywrap.ts` | Pure validation checks the complete IR structure and schema version `0.4.0`; generation checks the requested module. | +| Callable compilation | `src/core/callable-compiler.ts`, `src/contracts/value-contract.ts` | Resolved contracts describe arguments, overloads, conversion, validation, capabilities and diagnostics without I/O. | +| Wrapper generation | `src/core/generator.ts`, `src/core/emit-call.ts` | Declarations, call wrappers and return validators consume the resolved callable contracts. | | Runtime transport | `src/runtime/node.ts`, `src/runtime/subprocess-transport.ts`, `src/runtime/frame-codec.ts`, `runtime/python_bridge.py` | Node subprocess requests use JSONL and use `tywrap-frame/1` when a message exceeds one line. | | Python dispatch and encoding | `runtime/tywrap_bridge_core.py`, `runtime/safe_codec.py` | The bridge validates protocol input, then dispatches the requested call and returns JSON-safe values or versioned envelopes. | | JavaScript decoding | `src/utils/codec.ts`, `src/runtime/bridge-codec.ts` | Envelope shape and payload domains are checked before a decoded value reaches application code. | @@ -3341,22 +3482,32 @@ the declared return schema. ## IR and generated contracts -`generate()` in `src/tywrap.ts` invokes `python -m tywrap_ir --module `. -It validates the returned object before passing it to `CodeGenerator`, which -produces the wrapper source; `src/tywrap.ts` then writes -`.generated.ts` and the stable `.contract.json` beside it. The contract omits extractor metadata, -sorts object keys, and records the pinned IR representation. +`generate()` in `src/tywrap.ts` owns Python discovery, IR caching and file writes. +When it needs fresh IR, it invokes `python -m tywrap_ir --module `. +The pure IR validator checks the complete returned structure with located errors. +`compileContract()` resolves that IR using explicit conversion rules and runtime +capabilities. It does not access the filesystem, Python interpreter or runtime registry. + +The generator emits wrappers and declarations from those resolved contracts. +`generate()` writes `.generated.ts` and a stable `.contract.json`. +The saved contract contains canonical Python IR, not the resolved callable model. +It omits extractor metadata and sorts object keys. `contractInput` changes the source of IR. Instead of starting Python, generation -reads a saved contract and applies the same module and version validation. This +reads a saved contract and applies the same complete IR validation. This supports reproducible generation. A version mismatch is a hard failure: update the matching package pair and regenerate the contract. -`src/core/generator.ts` maps annotations to TypeScript and emits one -`createReturnValidator()` call per generated callable. Return schemas cover -primitive values, containers, definitions, and scientific markers. The -wrapper calls the active bridge and validates the resolved value before its -promise resolves. +The callable contract connects a result's logical type, decoded representation +and validator. A precise return declaration requires a supported conversion and +validation path. Unresolved results become `unknown` with diagnostics while +retaining available partial runtime checks. + +The generator emits `createReturnValidator()` calls from these contracts. +Return schemas cover primitives, containers, definitions and scientific markers. +Each wrapper calls the active bridge and validates the decoded result before its +promise resolves. See [callable contracts](https://bbopen.github.io/tywrap/maintainers/callable-contracts.md) for compiler +boundaries and [value contracts](https://bbopen.github.io/tywrap/maintainers/value-contracts.md) for conversion policy. ## Runtime bridges @@ -3371,6 +3522,9 @@ not edit it directly. Regenerate it from `runtime/tywrap_bridge_core.py` with the repository script. Pyodide uses JSON codec envelopes because pyarrow is not available in WASM. +The bridge awaits Python call results under the event loop owned by each +backend. See [coroutine calls](https://bbopen.github.io/tywrap/maintainers/coroutines.md) for timeout and disposal rules. + `HttpBridge` sends the same RPC and codec concepts to a remote Python service. The transport owns HTTP concerns while the codec and return validator preserve the client-side invariants. @@ -3400,10 +3554,12 @@ the required nested ndarray inside a torch envelope. `src/runtime/validators.ts` validates the value after decoding. A mismatch throws `BridgeValidationError` with the call site, declared type, and received -shape. Scientific values retain non-enumerable provenance from their envelope. +shape. Scientific values retain provenance from their envelope. Scalar scientific +results use per-call provenance because a JavaScript number cannot hold metadata. The validator checks the marker and, when the schema declares them, dimensions -and dtype without walking Arrow payload data. `unknown`, `void`, and `Any` -returns deliberately receive no runtime check. +and dtype without walking Arrow payload data. Explicit `unknown`, `void`, and +`Any` schemas perform no check. A result whose declaration became `unknown` can +still retain partial checks from its original annotation. ## One call end to end @@ -3426,6 +3582,124 @@ envelope. It defines the supported JSON domains and validation behavior. --- + +# Callable compilation contracts + +`tywrap_ir` emits IR 0.4. `validateIrContract()` checks required fields in +unknown JSON. Each diagnostic has a JSON path. Validation stops after 100,000 +array entries. + +`compileContract()` is an internal pure step. It accepts validated IR, +exported-name selection, value conversions, capabilities, and a generator. It +maps callable types from the validated IR. The selection input cannot change +those types. It returns the resolved module, callable records, diagnostics, and +TypeScript and declaration content. + +The compiler does not read files. It does not start Python. It does not read a +cache. It does not write files. It does not access a runtime registry. + +`generate()` owns Python discovery, cache reads, output comparison, and writes. +It validates IR and maps annotations, then calls `compileContract()` before +emission. Offline contract files omit extractor metadata for stable bytes. The +reader restores an empty metadata object. + +## Resolved callable data + +The compiler records each parameter and result, including overloads. Each record +has a Python type, direction, source path, and conversion result. One resolved +module model serves declarations, call wrappers, and return validators. + +Each value conversion uses revision 2 of +[value-contracts.v2.json](https://bbopen.github.io/tywrap/maintainers/value-contracts.v2.json). Do not infer a wire rule +from the TypeScript type. + +| Case | Result | +| --------------------- | ------------------------------------------------------------------------------------- | +| `int` | JSON number, JavaScript number, safe-integer constraint | +| `bytes` | Existing base64 envelope, decoded as `Uint8Array` | +| nested `dict[str, T]` | JSON record with the child conversion at every value path | +| `str \| int` | Selected union alternative with one child contract per option | +| `tuple[int, str]` | Exact JSON array with a contract for each index | +| float16 ndarray | Existing Arrow or JSON-fallback envelope, decoded as a numeric scalar or nested array | +| float16 Torch tensor | Outer `torch.float16` envelope with a nested `float16` ndarray | + +The compiler requires an explicit float16 dtype. An untyped ndarray or Torch +tensor stays unresolved. + +For an evaluated PyTorch annotation, use `torch.HalfTensor`. The compiler +accepts this exact class and leaves other Torch tensor classes unresolved. + +NumPy can spell `NDArray[np.float16]` as +`numpy.ndarray[tuple[Any, ...], numpy.dtype[numpy.float16]]`. The compiler reads +the dtype argument, not the shape wildcard. Only a supported scientific result +clears its matching external-annotation IR warning. Other external annotations +remain warnings. + +The codec records scalar ndarray dtype and rank for one call. A generated return +validator accepts a scalar only with matching proof. Nested proof follows its +parent and array index or record key. Array index `0` and `"0"` refer to the +same child. Equal numbers from separate calls do not share proof. Array and +tensor objects keep their identity-based marker proof. + +The compiler keeps Arrow int64 behavior outside this prototype. Existing Arrow +int64 values can decode as `bigint`. + +Selected local non-generic `TypedDict` classes use revision-2 record contracts +when every field has a supported conversion. Nested records and selected simple +aliases compose through the same resolver. Foreign and recursive names remain +unresolved. + +## Diagnostics and fallback + +Known unsupported cases create error diagnostics. The compiler changes the +affected generated type to `unknown`. `generate()` returns each diagnostic as a +warning, so `--fail-on-warn` rejects strict builds. + +- The default compiler capability covers coroutine execution in the in-repo Node + and Pyodide bridges. A caller can mark this capability unavailable when it + uses an older or custom bridge. The compiler then emits `unknown` and an error + diagnostic for async results. +- Dataclasses require an adapter owned by #339. The default capability stays + unavailable. An explicit output record conversion can use the adapter + capability when enabled. +- Non-string record keys require an explicit conversion. + +Unresolved annotations create warning diagnostics. Their result type is +`unknown`, including an output that contains `object` or a type variable. Python +`object` can hold a primitive value. A type variable has no validated conversion +to the decoded result. Neither annotation justifies a precise TypeScript return. + +The compiler keeps an existing best-effort return check when it widens a +declaration. For example, an unresolved `list[object]` still rejects a non-array +result, and a `DataFrame` annotation still requires a decoded marker. + +`Literal` returns keep their exact-value validator, but stay `unknown` until a +literal value contract exists. Unresolved literal overloads cannot select a +precise return at runtime. + +IR overload signatures stay separate from the implementation signature. The +extractor collects type variables from overload annotations. Generated +declarations retain each input-to-result relation. The hidden TypeScript +implementation accepts `unknown` values so it can cover every declared overload. + +At runtime, the wrapper selects the first supported overload that matches bound +arguments. This follows TypeScript declaration order. The compiler warns when +overload inputs may overlap, including an omitted optional argument. Python 3.10 +cannot expose registered overloads through `typing.get_overloads`; it keeps the +implementation signature and emits an IR warning. + +## Deferred work + +Revision 2 does not describe references or recursive aliases. The compiler +reports these cases as unresolved. A later value-contract revision can give them +a supported conversion. + +The client-binding work may consume the resolved callable model later. It must +remain opt-in. It must not add files to default generation or mutate the global +runtime registry. + +--- + # Menagerie Discipline @@ -3555,7 +3829,7 @@ console.log(await sin(pi / 4)); ## Value-returning APIs -v0.9 generated wrappers do not keep live Python class instances. Expose an +v0.10 generated wrappers do not keep live Python class instances. Expose an operation as a value-returning module function instead: ```ts diff --git a/docs/public/llms.txt b/docs/public/llms.txt index 9a2ef5ea..5f4088a2 100644 --- a/docs/public/llms.txt +++ b/docs/public/llms.txt @@ -11,6 +11,7 @@ ## Docs - [Getting Started](https://bbopen.github.io/tywrap/guide/getting-started): Installation, quick start, first wrapper +- [Migrating to 0.11](https://bbopen.github.io/tywrap/guide/migrating-to-0-11): Planned integer, float16, return-type and coroutine changes - [Agent Adoption](https://bbopen.github.io/tywrap/guide/agent-adoption): Deterministic project-adoption recipe for coding agents - [Configuration](https://bbopen.github.io/tywrap/guide/configuration): tywrap.config.ts / .json, all options - [Runtime Comparison](https://bbopen.github.io/tywrap/guide/runtimes/comparison): Which bridge to use and when diff --git a/docs/reference/api/index.md b/docs/reference/api/index.md index 26a5e3b5..2d4a6976 100644 --- a/docs/reference/api/index.md +++ b/docs/reference/api/index.md @@ -59,6 +59,12 @@ When `output.declaration` is enabled, `generate()` writes matching code. Simple `TypeVar` and callable `ParamSpec` declarations are preserved when tywrap can represent them safely. +Unresolved return annotations now emit `Promise` and a located warning. +This includes `TypeVar` and `ParamSpec` results without a supported value +conversion. Input generics remain in the declaration. Earlier versions could +emit `Promise` without validating the decoded value as `T`; callers must +narrow the result or use a supported concrete overload. + `generate()` returns: ```ts diff --git a/package-lock.json b/package-lock.json index 9a5af689..f95e87c4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "tywrap": "dist/cli.js" }, "devDependencies": { + "@playwright/test": "1.58.2", "@types/bun": "^1.3.11", "@types/node": "^25.5.2", "@types/three": "^0.183.1", @@ -31,6 +32,7 @@ "fast-check": "^4.6.0", "postprocessing": "^6.39.1", "prettier": "^3.8.1", + "pyodide": "0.28.1", "three": "^0.184.0", "tsd": "^0.33.0", "vite": "^8.0.8", @@ -787,6 +789,22 @@ "dev": true, "license": "MIT" }, + "node_modules/@playwright/test": { + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.58.2.tgz", + "integrity": "sha512-akea+6bHYBBfA9uQqSYmlJXn61cTa+jbO87xVLCWbTqbWadRVmhxlXATaOjOgcBaWU4ePo0wB41KMFv3o35IXA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.58.2" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/@rolldown/binding-android-arm64": { "version": "1.0.0-rc.15", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.15.tgz", @@ -5363,6 +5381,53 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright": { + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz", + "integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.58.2" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz", + "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/playwright/node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, "node_modules/plur": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/plur/-/plur-4.0.0.tgz", @@ -5525,8 +5590,8 @@ "version": "0.28.1", "resolved": "https://registry.npmjs.org/pyodide/-/pyodide-0.28.1.tgz", "integrity": "sha512-7O1jZdfUc4/9PAKzEIyLOh3yhxknTWA8xQaCfZ4R56pOnchS909x2sqt2Wh+qHf+b7MzyB8igE5ZzYdP1pZN5w==", + "dev": true, "license": "MPL-2.0", - "peer": true, "dependencies": { "ws": "^8.5.0" }, @@ -7522,8 +7587,8 @@ "version": "8.18.3", "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", + "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=10.0.0" }, diff --git a/package.json b/package.json index d071222f..d44fa1f9 100644 --- a/package.json +++ b/package.json @@ -128,6 +128,7 @@ "yargs": "^18.0.0" }, "devDependencies": { + "@playwright/test": "1.58.2", "@types/bun": "^1.3.11", "@types/node": "^25.5.2", "@types/three": "^0.183.1", @@ -143,6 +144,7 @@ "fast-check": "^4.6.0", "postprocessing": "^6.39.1", "prettier": "^3.8.1", + "pyodide": "0.28.1", "three": "^0.184.0", "tsd": "^0.33.0", "vite": "^8.0.8", diff --git a/runtime/frame_codec.py b/runtime/frame_codec.py index bfb00662..58361984 100644 --- a/runtime/frame_codec.py +++ b/runtime/frame_codec.py @@ -100,22 +100,27 @@ def encode_frames( if total_bytes is None: total_bytes = utf8_byte_length(logical_json) - # Walk codepoints, accumulating UTF-8 bytes into the current slice until the - # next codepoint would exceed max_frame_bytes; that boundary is, by - # construction, a codepoint boundary so no multi-byte sequence is split. - slices: List[str] = [] - current_chars: List[str] = [] - current_bytes = 0 - for ch in logical_json: - ch_bytes = _utf8_bytes_of_codepoint(ord(ch)) - if current_bytes + ch_bytes > max_frame_bytes and current_chars: - slices.append(''.join(current_chars)) - current_chars = [] - current_bytes = 0 - current_chars.append(ch) - current_bytes += ch_bytes - # Always emit a final slice (covers the empty-string case: one empty frame). - slices.append(''.join(current_chars)) + if logical_json.isascii(): + # Each ASCII character is one byte, so direct slices keep byte boundaries. + slices = [ + logical_json[start:start + max_frame_bytes] + for start in range(0, len(logical_json), max_frame_bytes) + ] or [''] + else: + # Walk codepoints so a frame never splits a multi-byte UTF-8 sequence. + slices = [] + current_chars: List[str] = [] + current_bytes = 0 + for ch in logical_json: + ch_bytes = _utf8_bytes_of_codepoint(ord(ch)) + if current_bytes + ch_bytes > max_frame_bytes and current_chars: + slices.append(''.join(current_chars)) + current_chars = [] + current_bytes = 0 + current_chars.append(ch) + current_bytes += ch_bytes + # Always emit a final slice for a non-empty Unicode payload. + slices.append(''.join(current_chars)) total = len(slices) return [ diff --git a/runtime/tywrap_bridge_core.py b/runtime/tywrap_bridge_core.py index 90b5b2c9..ac04e0e4 100644 --- a/runtime/tywrap_bridge_core.py +++ b/runtime/tywrap_bridge_core.py @@ -565,13 +565,17 @@ def serialize_dataframe_json(obj): } -def serialize_series(obj, *, force_json_markers): +def serialize_series(obj, *, force_json_markers, path='result'): """ Encode a pandas Series as a single-column Arrow Table stream (the JS decoder contract is "table-like"); JSON when force_json_markers is set. """ if force_json_markers: - return serialize_series_json(obj) + return serialize_series_json(obj, path=path) + name = getattr(obj, 'name', None) + _check_terminal_json_integers( + encode_value(name, allow_nan=False), _serialize_path(path, 'name') + ) try: import pyarrow as pa # type: ignore except Exception as exc: @@ -591,13 +595,13 @@ def serialize_series(obj, *, force_json_markers): 'codecVersion': CODEC_VERSION, 'encoding': 'arrow', 'b64': b64, - 'name': getattr(obj, 'name', None), + 'name': name, } except Exception as exc: raise RuntimeError('Arrow encoding failed for pandas.Series') from exc -def serialize_series_json(obj): +def serialize_series_json(obj, *, path='result'): """JSON fallback for Series values that JavaScript can represent safely.""" import pandas as pd # type: ignore @@ -615,12 +619,16 @@ def serialize_series_json(obj): _normalize_pandas_json_scalar(value, f'Series value at position {position}', pd) for position, value in enumerate(data) ] + name = getattr(obj, 'name', None) + _check_terminal_json_integers( + encode_value(name, allow_nan=False), _serialize_path(path, 'name') + ) return { '__tywrap__': 'series', 'codecVersion': CODEC_VERSION, 'encoding': 'json', 'data': data, - 'name': getattr(obj, 'name', None), + 'name': name, } @@ -688,7 +696,7 @@ def _normalize_pandas_json_scalar(value, location, pd): ) -def serialize_sparse_matrix(obj): +def serialize_sparse_matrix(obj, *, path='result'): """ Serialize scipy sparse matrices into structured JSON envelopes (json-only; there is no Arrow path). Preserves sparsity; rejects unsupported formats and @@ -715,6 +723,32 @@ def serialize_sparse_matrix(obj): 'Complex scipy sparse matrices are not supported by the JSON codec; ' 'split into real/imag components explicitly before returning' ) + if getattr(obj.dtype, 'kind', None) in ('i', 'u') and obj.data.size and ( + (obj.data < -JS_SAFE_INTEGER_MAX).any() + or (obj.data > JS_SAFE_INTEGER_MAX).any() + ): + raise RuntimeError( + 'JSON scipy sparse encoding cannot safely represent data outside the ' + 'JavaScript safe integer range; cast or encode the values explicitly' + ) + + for index, dimension in enumerate(obj.shape): + if int.__int__(dimension) > JS_SAFE_INTEGER_MAX: + raise RuntimeError( + f'Unsafe Python integer at {_serialize_path(_serialize_path(path, "shape"), index)}: ' + f'{dimension} is outside the JavaScript safe integer range' + ) + index_fields = ('indices', 'indptr') if fmt in ('csr', 'csc') else ('row', 'col') + for field in index_fields: + values = getattr(obj, field) + if values.size and ( + (values < -JS_SAFE_INTEGER_MAX).any() + or (values > JS_SAFE_INTEGER_MAX).any() + ): + raise RuntimeError( + f'JSON scipy sparse encoding cannot safely represent {field} at ' + f'{_serialize_path(path, field)} outside the JavaScript safe integer range' + ) if fmt in ('csr', 'csc'): data = obj.data.tolist() @@ -845,7 +879,7 @@ def serialize_torch_tensor(obj, *, force_json_markers, torch_allow_copy=False): return envelope -def serialize_sklearn_estimator(obj): +def serialize_sklearn_estimator(obj, *, path): """Serialize sklearn estimators as metadata only (json-only); no pickling.""" try: import sklearn # noqa: F401 @@ -861,7 +895,11 @@ def serialize_sklearn_estimator(obj): # params here for parity with the response codec. for key, value in params.items(): try: - json.dumps(value, allow_nan=False) + encoded = json.dumps(value, allow_nan=False) + param_path = _serialize_path(_serialize_path(path, 'params'), str(key)) + _check_terminal_json_integers(encoded, param_path) + except RuntimeError: + raise except (TypeError, ValueError) as exc: raise RuntimeError( f'scikit-learn estimator param {key!r} is not JSON-serializable ' @@ -881,6 +919,25 @@ def serialize_sklearn_estimator(obj): } +def _check_terminal_json_integers(encoded, path): + """Check integer tokens in a small JSON metadata value before emission.""" + stack = [(json.loads(encoded), path)] + while stack: + current, current_path = stack.pop() + if type(current) is int: + _serialize_leaf(current, current_path) + elif isinstance(current, dict): + stack.extend( + (item, _serialize_path(current_path, key)) + for key, item in current.items() + ) + elif isinstance(current, list): + stack.extend( + (item, _serialize_path(current_path, index)) + for index, item in enumerate(current) + ) + + _NO_PYDANTIC = object() @@ -954,11 +1011,11 @@ def _serialize_scientific(obj, *, force_json_markers, torch_allow_copy, depth, p return serialize_dataframe(obj, force_json_markers=force_json_markers) if is_pandas_series(obj): _check_serialize_depth(depth, path) - return serialize_series(obj, force_json_markers=force_json_markers) + return serialize_series(obj, force_json_markers=force_json_markers, path=path) elif package == 'scipy' and 'scipy.sparse' in sys.modules: if is_scipy_sparse(obj): _check_serialize_depth(depth, path) - return serialize_sparse_matrix(obj) + return serialize_sparse_matrix(obj, path=path) elif package == 'torch' and 'torch' in sys.modules: if is_torch_tensor(obj): _check_serialize_depth(depth, path) @@ -972,7 +1029,7 @@ def _serialize_scientific(obj, *, force_json_markers, torch_allow_copy, depth, p # estimators live outside the 'sklearn' package and must still get the # estimator serializer (and its param-naming errors). _check_serialize_depth(depth, path) - return serialize_sklearn_estimator(obj) + return serialize_sklearn_estimator(obj, path=path) return _NO_SCIENTIFIC @@ -995,21 +1052,42 @@ def _needs_serialize_visit(value): """Return whether value needs container or scientific traversal work.""" if type(value) in (type(None), bool, int, float, str): return False - if type(value) in (dict, list, tuple): + if isinstance(value, (dict, list, tuple, set, frozenset)): return True package = type(value).__module__.split('.', 1)[0] if package in ('numpy', 'pandas', 'scipy', 'torch'): return True - return 'sklearn.base' in sys.modules and is_sklearn_estimator(value) + return callable(getattr(value, 'model_dump', None)) or ( + 'sklearn.base' in sys.modules and is_sklearn_estimator(value) + ) -def _serialize_leaf(value): +def _serialize_leaf(value, path): """Apply non-container conversions without allocating a traversal frame.""" + integer_value = int.__int__(value) if isinstance(value, int) and not isinstance(value, bool) else None + if integer_value is not None and ( + integer_value < -JS_SAFE_INTEGER_MAX or integer_value > JS_SAFE_INTEGER_MAX + ): + raise RuntimeError( + f'Unsafe Python integer at {path}: {integer_value} is outside the JavaScript safe ' + 'integer range; return an explicit string or use an Arrow integer column' + ) if type(value) in (type(None), bool, int, float, str): return value + np = sys.modules.get('numpy') + if np is not None and isinstance(value, np.generic): + extracted = value.item() + if isinstance(extracted, np.generic): + raise TypeError( + f'NumPy scalar at {path} did not convert to a JSON value; ' + 'cast it explicitly before returning' + ) + return _serialize_leaf(extracted, path) pydantic_value = serialize_pydantic(value) if pydantic_value is not _NO_PYDANTIC: return pydantic_value + if isinstance(value, (set, frozenset)): + return list(value) stdlib_value = serialize_stdlib(value) if stdlib_value is not None: return stdlib_value @@ -1037,6 +1115,9 @@ def serialize(obj, *, force_json_markers, torch_allow_copy=False): while stack: frame = stack.pop() action = frame[0] + if action == 'release-model': + active_ids.remove(frame[1]) + continue if action == 'dict': _, current, depth, path, parent, key, output, iterator = frame try: @@ -1057,22 +1138,23 @@ def serialize(obj, *, force_json_markers, torch_allow_copy=False): if _needs_serialize_visit(item): stack.append(('visit', item, depth + 1, child_path, output, item_key)) else: - output[item_key] = _serialize_leaf(item) + output[item_key] = _serialize_leaf(item, child_path) continue if action == 'sequence': _, current, depth, path, parent, key, output, index = frame if index == len(output): active_ids.remove(id(current)) - parent[key] = output if type(current) is list else tuple(output) + parent[key] = output if isinstance(current, list) else tuple(output) continue stack.append(('sequence', current, depth, path, parent, key, output, index + 1)) item = current[index] + child_path = _serialize_path(path, index) if _needs_serialize_visit(item): stack.append( - ('visit', item, depth + 1, _serialize_path(path, index), output, index) + ('visit', item, depth + 1, child_path, output, index) ) else: - output[index] = _serialize_leaf(item) + output[index] = _serialize_leaf(item, child_path) continue _, current, depth, path, parent, key = frame @@ -1085,7 +1167,7 @@ def serialize(obj, *, force_json_markers, torch_allow_copy=False): path=path, ) except Exception as exc: - if path == 'result': + if path == 'result' and 'safe integer range' not in str(exc): raise raise RuntimeError(f'Scientific value serialization failed at {path}: {exc}') from exc if scientific is not _NO_SCIENTIFIC: @@ -1106,8 +1188,25 @@ def serialize(obj, *, force_json_markers, torch_allow_copy=False): parent[key] = scientific continue - container_type = type(current) - if container_type in (dict, list, tuple): + if callable(getattr(current, 'model_dump', None)): + _check_serialize_depth(depth, path) + visited_nodes += 1 + _check_serialize_nodes(visited_nodes, path) + current_id = id(current) + if current_id in active_ids: + raise RuntimeError(f'Circular model conversion detected at {path}') + active_ids.add(current_id) + normalized = _serialize_leaf(current, path) + if normalized is current: + raise RuntimeError(f'Circular model conversion detected at {path}') + stack.append(('release-model', current_id)) + if _needs_serialize_visit(normalized): + stack.append(('visit', normalized, depth + 1, path, parent, key)) + else: + parent[key] = _serialize_leaf(normalized, path) + continue + + if isinstance(current, (dict, list, tuple)): _check_serialize_depth(depth, path) visited_nodes += 1 _check_serialize_nodes(visited_nodes, path) @@ -1116,7 +1215,7 @@ def serialize(obj, *, force_json_markers, torch_allow_copy=False): raise RuntimeError(f'Circular reference detected at {path}') active_ids.add(current_id) - if container_type is dict: + if isinstance(current, dict): output = {} parent[key] = output stack.append( @@ -1125,12 +1224,18 @@ def serialize(obj, *, force_json_markers, torch_allow_copy=False): continue output = [None] * len(current) - if container_type is list: + if isinstance(current, list): parent[key] = output stack.append(('sequence', current, depth, path, parent, key, output, 0)) continue - parent[key] = _serialize_leaf(current) + normalized = _serialize_leaf(current, path) + if normalized is not current and _needs_serialize_visit(normalized): + stack.append(('visit', normalized, depth, path, parent, key)) + elif normalized is not current: + parent[key] = _serialize_leaf(normalized, path) + else: + parent[key] = normalized return root[0] @@ -1342,11 +1447,9 @@ def coerce_dict(value, key): return value -def handle_call( +def _invoke_call( params, *, - force_json_markers, - torch_allow_copy, allowed_modules, allow_private_attrs, has_envelope_markers, @@ -1360,7 +1463,72 @@ def handle_call( # calls, which the generated wrapper routes through call() rather than an # instance handle. resolve_allowed_attr_path guards each segment. func = resolve_allowed_attr_path(mod, function_name, allow_private_attrs=allow_private_attrs) - res = func(*args, **kwargs) + return func(*args, **kwargs) + + +def _reject_generator(value): + import inspect + + if inspect.isgenerator(value): + raise TypeError('Generator results are not supported by tywrap RPC') + if inspect.isasyncgen(value): + raise TypeError('Async generator results are not supported by tywrap RPC') + + +async def _await_result(value): + return await value + + +def handle_call( + params, + *, + force_json_markers, + torch_allow_copy, + allowed_modules, + allow_private_attrs, + has_envelope_markers, +): + """Run one call. The serial subprocess owns a fresh loop for awaitables.""" + import asyncio + import inspect + + res = _invoke_call( + params, + allowed_modules=allowed_modules, + allow_private_attrs=allow_private_attrs, + has_envelope_markers=has_envelope_markers, + ) + _reject_generator(res) + if inspect.isawaitable(res): + # asyncio.run requires a coroutine, while user code may return any + # awaitable. It closes the per-call loop on Python 3.10 through 3.12. + res = asyncio.run(_await_result(res)) + _reject_generator(res) + return serialize(res, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy) + + +async def handle_call_async( + params, + *, + force_json_markers, + torch_allow_copy, + allowed_modules, + allow_private_attrs, + has_envelope_markers, +): + """Run one call on the caller's loop, which Pyodide owns.""" + import inspect + + res = _invoke_call( + params, + allowed_modules=allowed_modules, + allow_private_attrs=allow_private_attrs, + has_envelope_markers=has_envelope_markers, + ) + _reject_generator(res) + if inspect.isawaitable(res): + res = await res + _reject_generator(res) return serialize(res, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy) @@ -1463,6 +1631,52 @@ def dispatch_request( return {'id': mid, 'protocol': PROTOCOL, 'result': result} +async def dispatch_request_async( + msg, + *, + bridge, + pid, + force_json_markers, + allow_nan=False, + python_version=None, + torch_allow_copy=False, + arrow_available_override=None, + allowed_modules=None, + allow_private_attrs=False, + has_envelope_markers=True, +): + """Dispatch on the caller's event loop and return one response envelope.""" + mid = require_protocol(msg) + method = msg.get('method') + if not isinstance(method, str): + raise ProtocolError('Missing method') + params = coerce_dict(msg.get('params'), 'params') + if method == 'call': + result = await handle_call_async( + params, + force_json_markers=force_json_markers, + torch_allow_copy=torch_allow_copy, + allowed_modules=allowed_modules, + allow_private_attrs=allow_private_attrs, + has_envelope_markers=has_envelope_markers, + ) + elif method == 'meta': + if python_version is None: + import sys + python_version = sys.version.split()[0] + codec_fallback = 'json' if force_json_markers else 'none' + result = build_meta( + bridge=bridge, + pid=pid, + python_version=python_version, + codec_fallback=codec_fallback, + arrow_available_override=arrow_available_override, + ) + else: + raise ProtocolError(f'Unknown method: {method}') + return {'id': mid, 'protocol': PROTOCOL, 'result': result} + + def build_error_payload(mid, exc, *, include_traceback): """ Build a protocol error response. Protocol/validation errors omit traceback; diff --git a/scripts/fetch-pyodide-package.mjs b/scripts/fetch-pyodide-package.mjs new file mode 100644 index 00000000..3ede41eb --- /dev/null +++ b/scripts/fetch-pyodide-package.mjs @@ -0,0 +1,20 @@ +import { createHash } from 'node:crypto'; +import { readFile, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +const packageName = process.argv[2]; +if (packageName !== 'numpy') throw new Error('Only the reviewed numpy asset is allowed'); + +const directory = join(process.cwd(), 'node_modules', 'pyodide'); +const lock = JSON.parse(await readFile(join(directory, 'pyodide-lock.json'), 'utf8')); +const metadata = lock.packages?.[packageName]; +if (!metadata?.file_name || !metadata?.sha256) throw new Error(`Missing locked ${packageName} metadata`); + +const url = `https://cdn.jsdelivr.net/pyodide/v0.28.1/full/${metadata.file_name}`; +const response = await fetch(url); +if (!response.ok) throw new Error(`Could not fetch ${url}: ${response.status}`); +const bytes = Buffer.from(await response.arrayBuffer()); +const digest = createHash('sha256').update(bytes).digest('hex'); +if (digest !== metadata.sha256) throw new Error(`Checksum mismatch for ${metadata.file_name}`); +await writeFile(join(directory, metadata.file_name), bytes); +console.log(`Fetched ${metadata.file_name} with locked sha256 ${digest}`); diff --git a/scripts/generate-llms-full.mjs b/scripts/generate-llms-full.mjs index 23859f82..50b8f2f4 100644 --- a/scripts/generate-llms-full.mjs +++ b/scripts/generate-llms-full.mjs @@ -4,6 +4,7 @@ import { join } from 'node:path'; const orderedDocs = [ 'docs/index.md', 'docs/guide/getting-started.md', + 'docs/guide/migrating-to-0-11.md', 'docs/guide/agent-adoption.md', 'docs/guide/configuration.md', 'docs/guide/runtimes/comparison.md', @@ -21,15 +22,22 @@ const orderedDocs = [ 'docs/transport-framing.md', 'docs/reference/api/index.md', 'docs/maintainers/architecture.md', + 'docs/maintainers/callable-contracts.md', 'docs/maintainers/menagerie.md', 'docs/examples/index.md', 'docs/troubleshooting/index.md', ]; -// Internal / forward-looking docs kept out of the agent-facing llms-full bundle. +// Keep design proposals and review records outside the agent guide. const excludedDocs = new Set([ 'docs/perf-baselines.md', 'docs/release.md', + 'docs/maintainers/client-binding-design.md', + 'docs/maintainers/client-binding-prototype-review.md', + 'docs/maintainers/coroutines.md', + 'docs/maintainers/value-contract-prototypes.md', + 'docs/maintainers/value-contracts.md', + 'docs/maintainers/architecture-decision-0.11.md', ]); async function collectDocs(dir) { diff --git a/scripts/print-pyodide-ci-evidence.mjs b/scripts/print-pyodide-ci-evidence.mjs new file mode 100644 index 00000000..cca3d42d --- /dev/null +++ b/scripts/print-pyodide-ci-evidence.mjs @@ -0,0 +1,44 @@ +import { readFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { dirname, join } from 'node:path'; + +import packageJson from '../package.json' with { type: 'json' }; + +const require = createRequire(import.meta.url); +const browsersPath = join(dirname(require.resolve('playwright-core')), 'browsers.json'); +const browsers = JSON.parse(await readFile(browsersPath, 'utf8')); + +const pyodideVersion = packageJson.devDependencies.pyodide; +const playwrightVersion = packageJson.devDependencies['@playwright/test']; +const installedPyodide = JSON.parse( + await readFile(join(process.cwd(), 'node_modules', 'pyodide', 'package.json'), 'utf8') +).version; +const installedPlaywright = JSON.parse( + await readFile(join(process.cwd(), 'node_modules', '@playwright', 'test', 'package.json'), 'utf8') +).version; +const installedPlaywrightCore = JSON.parse( + await readFile(join(process.cwd(), 'node_modules', 'playwright-core', 'package.json'), 'utf8') +).version; +const chromium = browsers.browsers.find(browser => browser.name === 'chromium'); +const nodeMajor = Number(process.versions.node.split('.')[0]); + +if (pyodideVersion !== '0.28.1' || playwrightVersion !== '1.58.2') { + throw new Error('Pyodide and Playwright must use the reviewed exact versions'); +} +if ( + installedPyodide !== pyodideVersion || + installedPlaywright !== playwrightVersion || + installedPlaywrightCore !== playwrightVersion +) { + throw new Error('Installed Pyodide and Playwright versions differ from the reviewed pins'); +} +if (!Number.isInteger(nodeMajor) || nodeMajor < 20) { + throw new Error(`Pyodide browser evidence requires Node 20 or later, found ${process.version}`); +} +if (!chromium?.revision) { + throw new Error('Playwright did not declare a Chromium revision'); +} + +console.log(`Node ${process.version}`); +console.log(`Installed Pyodide ${installedPyodide}; CDN version ${pyodideVersion}`); +console.log(`Installed Playwright ${installedPlaywright}, Chromium revision ${chromium.revision}`); diff --git a/src/contracts/value-contract.ts b/src/contracts/value-contract.ts new file mode 100644 index 00000000..b8b8c207 --- /dev/null +++ b/src/contracts/value-contract.ts @@ -0,0 +1,145 @@ +/** Internal value policy consumed by codecs and callable-contract generation. */ +export const VALUE_CONTRACT_REVISION = 2 as const; + +/** Exact integer mode uses a separate semantic contract revision. */ +export const VALUE_CONTRACT_V3_REVISION = 3 as const; + +export type ValueContractRevision = + | typeof VALUE_CONTRACT_REVISION + | typeof VALUE_CONTRACT_V3_REVISION; + +/** JSON numbers can carry Python integers exactly only within this range. */ +export const MAX_SAFE_JSON_INTEGER = 2 ** 53 - 1; + +type CommonValueContractLeaf = + | { readonly kind: 'null'; readonly wire: 'json'; readonly decodedAs: 'null' } + | { readonly kind: 'boolean'; readonly wire: 'json'; readonly decodedAs: 'boolean' } + | { + readonly kind: 'integer'; + readonly wire: 'json'; + readonly decodedAs: 'number'; + readonly constraint: 'safe-integer'; + } + | { + readonly kind: 'float'; + readonly wire: 'json'; + readonly decodedAs: 'number'; + readonly constraint: 'finite'; + } + | { readonly kind: 'string'; readonly wire: 'json'; readonly decodedAs: 'string' } + | { readonly kind: 'bytes'; readonly wire: 'base64-envelope'; readonly decodedAs: 'Uint8Array' } + | { + readonly kind: 'ndarray-float16'; + readonly wire: 'arrow' | 'json-fallback'; + readonly decodedAs: 'nested-array-or-scalar'; + readonly element: Extract; + readonly dtype: 'float16'; + readonly rank?: number; + } + | { + readonly kind: 'torch-float16'; + readonly wire: 'ndarray-envelope'; + readonly decodedAs: 'tensor-record'; + readonly dtype: 'torch.float16'; + readonly value: Extract; + } + | { + readonly kind: 'unsupported'; + readonly wire: 'none'; + readonly decodedAs: 'never'; + readonly reason: string; + readonly guidance: string; + }; + +interface SequenceContract { + readonly kind: 'sequence'; + readonly wire: 'json'; + readonly decodedAs: 'array'; + readonly item: TValue; +} + +interface TupleContract { + readonly kind: 'tuple'; + readonly wire: 'json'; + readonly decodedAs: 'array'; + readonly items: readonly TValue[]; +} + +interface UnionContract { + readonly kind: 'union'; + readonly wire: 'selected-option'; + readonly decodedAs: 'selected-option'; + readonly options: readonly [TValue, TValue, ...TValue[]]; +} + +interface RecordContract { + readonly kind: 'record'; + readonly wire: 'json'; + readonly decodedAs: 'object'; + readonly fields: readonly ValueContractField[]; + readonly additionalValues?: TValue; +} + +interface V2SequenceContract extends SequenceContract {} +interface V2TupleContract extends TupleContract {} +interface V2UnionContract extends UnionContract {} +interface V2RecordContract extends RecordContract {} + +/** Revision 2 remains the default safe-number value contract. */ +export type ValueContract = + | CommonValueContractLeaf + | V2SequenceContract + | V2TupleContract + | V2UnionContract + | V2RecordContract; + +export interface ExactIntegerValueContract { + readonly kind: 'integer-exact'; + readonly wire: 'decimal-string-envelope'; + readonly decodedAs: 'bigint'; + readonly constraint: 'exact-integer'; +} + +interface V3SequenceContract extends SequenceContract {} +interface V3TupleContract extends TupleContract {} +interface V3UnionContract extends UnionContract {} +interface V3RecordContract extends RecordContract {} + +/** Revision 3 adds exact integers without changing revision 2. */ +export type ValueContractV3 = + | CommonValueContractLeaf + | ExactIntegerValueContract + | V3SequenceContract + | V3TupleContract + | V3UnionContract + | V3RecordContract; + +export interface ValueContractField { + readonly name: string; + readonly value: TValue; + readonly required: boolean; +} + +export function containsExactInteger(value: ValueContractV3): boolean { + switch (value.kind) { + case 'integer-exact': + return true; + case 'sequence': + return containsExactInteger(value.item); + case 'tuple': + return value.items.some(containsExactInteger); + case 'union': + return value.options.some(containsExactInteger); + case 'record': + return ( + value.fields.some(field => containsExactInteger(field.value)) || + (value.additionalValues !== undefined && containsExactInteger(value.additionalValues)) + ); + default: + return false; + } +} + +export function isSafeJsonInteger(value: number): boolean { + return Number.isInteger(value) && Math.abs(value) <= MAX_SAFE_JSON_INTEGER; +} diff --git a/src/core/annotation-parser.ts b/src/core/annotation-parser.ts index 5dfc2864..9bf6543a 100644 --- a/src/core/annotation-parser.ts +++ b/src/core/annotation-parser.ts @@ -16,10 +16,14 @@ export function parseAnnotationToPythonType( (options.typeParameters ?? []).map(param => [param.name, param] as const) ); const modulePrefixes = ['', 'typing.', 'typing_extensions.', 'collections.abc.'] as const; + let numpyShapeDepth = 0; const unknownType = (): PythonType => ({ kind: 'custom', name: 'Any', module: 'typing' }); const recordUnknown = (name: string): void => { + if (numpyShapeDepth > 0) { + return; + } try { onUnknownTypeName?.(name); } catch { @@ -495,8 +499,22 @@ export function parseAnnotationToPythonType( const generic = splitGenericInvocation(raw); if (generic) { - const typeArgs = splitTopLevel(generic.inner, ',').map(part => parse(part.trim(), depth + 1)); const qualified = splitQualifiedName(generic.name); + const parts = splitTopLevel(generic.inner, ','); + const numpyArrayShape = + qualified.module === 'numpy' && qualified.name === 'ndarray' && parts.length === 2; + const typeArgs = parts.map((part, index) => { + if (!numpyArrayShape || index !== 0) { + return parse(part.trim(), depth + 1); + } + // NumPy's first ndarray argument describes shape, not decoded value type. + numpyShapeDepth += 1; + try { + return parse(part.trim(), depth + 1); + } finally { + numpyShapeDepth -= 1; + } + }); return { kind: 'generic', name: qualified.name, diff --git a/src/core/callable-compiler.ts b/src/core/callable-compiler.ts new file mode 100644 index 00000000..96b0c2cd --- /dev/null +++ b/src/core/callable-compiler.ts @@ -0,0 +1,1456 @@ +/** + * Pure callable compilation. + * + * `generate()` owns discovery, caching, and writes. This module owns the + * deterministic step between validated IR and generated wrapper files. + */ + +import { + VALUE_CONTRACT_REVISION, + VALUE_CONTRACT_V3_REVISION, + containsExactInteger, + type ValueContractField, + type ValueContractRevision, + type ValueContractV3, +} from '../contracts/value-contract.js'; +import type { + GeneratedCode, + Parameter, + PythonFunction, + PythonModule, + PythonType, +} from '../types/index.js'; +import type { CodeGenerator } from './generator.js'; +import type { ValidatedIrContract } from './ir-contract.js'; +import { transformIrToTsModel } from './ir-model.js'; + +export type CallableDirection = 'input' | 'output'; + +export type CallableCapability = + | 'value-rpc' + | 'return-validation' + | 'scientific-ndarray' + | 'scientific-torch' + | 'coroutine-execution' + | 'dataclass-adapter' + | 'exact-integer-adapter'; + +export interface CapabilityDescription { + name: CallableCapability; + available: boolean; + guidance: string; +} + +export interface ValueConversionRequest { + direction: CallableDirection; + logicalType: PythonType; + path: string; + /** Internal recursion counter. Revision 2 rejects contracts deeper than 64 nodes. */ + depth?: number; + /** Compile-local resolver for nested named values. */ + resolveNested?: (request: ValueConversionRequest) => ValueResolution; + /** Exact local names already being expanded, used to stop recursive aliases. */ + activeNames?: readonly string[]; +} + +export interface SupportedValueResolution { + status: 'supported'; + value: ValueContractV3; +} + +export interface UnsupportedValueResolution { + status: 'unsupported'; + reason: string; + guidance: string; +} + +export interface UnresolvedValueResolution { + status: 'unresolved'; + annotation: string; +} + +export type ValueResolution = + | SupportedValueResolution + | UnsupportedValueResolution + | UnresolvedValueResolution; + +/** + * Maps an internal Python type to the frozen #343 value policy. + * + * The compiler does not infer wire behavior from a TypeScript spelling. + */ +export interface ValueConversionDescription { + revision: ValueContractRevision; + resolve(request: ValueConversionRequest): ValueResolution; +} + +export interface CallableCompilationDiagnostic { + severity: 'warning' | 'error'; + code: + | 'conversion-unresolved' + | 'conversion-unsupported' + | 'capability-unavailable' + | 'coroutine-unsupported' + | 'dataclass-unsupported' + | 'overload-ambiguous'; + path: string; + message: string; +} + +export interface ResolvedCallableValue { + direction: CallableDirection; + path: string; + logicalType: PythonType; + resolution: ValueResolution; +} + +export interface ResolvedCallable { + name: string; + path: string; + parameters: readonly ResolvedCallableValue[]; + result: ResolvedCallableValue; + overloadParameters: readonly (readonly ResolvedCallableValue[])[]; + overloadResults: readonly ResolvedCallableValue[]; + requiredCapabilities: readonly CallableCapability[]; +} + +export interface CompiledFile { + kind: 'typescript' | 'declaration'; + content: string; +} + +export interface CompiledContract { + /** Validated IR identity. It is retained for diagnostics and reproducibility. */ + ir: Pick; + /** Resolved model consumed by declarations, wrappers, and return validators. */ + module: PythonModule; + callables: readonly ResolvedCallable[]; + diagnostics: readonly CallableCompilationDiagnostic[]; + files: readonly CompiledFile[]; + generated: GeneratedCode; +} + +export interface CompileContractOptions { + /** Select exported names only. The compiler derives all types from validated IR. */ + module: PythonModule; + /** The generator is synchronous and performs no filesystem or runtime work. */ + generator: Pick; + conversion: ValueConversionDescription; + capabilities: readonly CapabilityDescription[]; + annotatedJSDoc?: boolean; +} + +const UNKNOWN_TYPE: PythonType = { kind: 'custom', name: 'Any', module: 'typing' }; + +export const DEFAULT_CALLABLE_CAPABILITIES: readonly CapabilityDescription[] = [ + { + name: 'value-rpc', + available: true, + guidance: 'Use the existing tywrap/1 value RPC transport.', + }, + { + name: 'return-validation', + available: true, + guidance: 'Generate a return validator for supported decoded values.', + }, + { + name: 'scientific-ndarray', + available: true, + guidance: 'Keep the existing ndarray Arrow envelope and JSON fallback.', + }, + { + name: 'scientific-torch', + available: true, + guidance: 'Reuse the ndarray conversion inside the existing Torch envelope.', + }, + { + name: 'coroutine-execution', + available: true, + guidance: 'Use a runtime bridge that awaits Python coroutine results.', + }, + { + name: 'dataclass-adapter', + available: false, + guidance: + 'Use a TypedDict or an explicit record adapter until #339 defines dataclass conversion.', + }, + { + name: 'exact-integer-adapter', + available: false, + guidance: 'Bind a revision-3 exact integer provider before generating this callable.', + }, +]; + +function leafName(type: PythonType): string | null { + if (type.kind !== 'custom' && type.kind !== 'generic') { + return null; + } + return type.name.split('.').at(-1) ?? null; +} + +function annotationName(type: PythonType): string { + switch (type.kind) { + case 'primitive': + return type.name; + case 'custom': + case 'generic': + return type.module ? `${type.module}.${type.name}` : type.name; + default: + return type.kind; + } +} + +function firstUnresolvedChild( + resolutions: readonly ValueResolution[] +): UnsupportedValueResolution | UnresolvedValueResolution | null { + return resolutions.find(resolution => resolution.status !== 'supported') ?? null; +} + +function rootWireKinds(value: ValueContractV3): ValueContractV3['kind'][] { + return value.kind === 'union' ? value.options.flatMap(rootWireKinds) : [value.kind]; +} + +function resolveSequence( + item: PythonType, + request: ValueConversionRequest, + conversion: Pick +): ValueResolution { + const child = conversion.resolve({ + ...request, + logicalType: item, + path: `${request.path}[]`, + depth: (request.depth ?? 0) + 1, + }); + if (child.status !== 'supported') { + return child; + } + return { + status: 'supported', + value: { kind: 'sequence', wire: 'json', decodedAs: 'array', item: child.value }, + }; +} + +function resolveRecord( + valueType: PythonType, + request: ValueConversionRequest, + conversion: Pick +): ValueResolution { + const child = conversion.resolve({ + ...request, + logicalType: valueType, + path: `${request.path}{value}`, + depth: (request.depth ?? 0) + 1, + }); + if (child.status !== 'supported') { + return child; + } + return { + status: 'supported', + value: { + kind: 'record', + wire: 'json', + decodedAs: 'object', + fields: [], + additionalValues: child.value, + }, + }; +} + +function resolveTuple( + items: readonly PythonType[], + request: ValueConversionRequest, + conversion: Pick +): ValueResolution { + if (items.length === 0) { + return { + status: 'supported', + value: { + kind: 'tuple', + wire: 'json', + decodedAs: 'array', + items: [], + }, + }; + } + if (items.length === 2 && items[1]?.kind === 'custom' && items[1].name === '...') { + return resolveSequence(items[0]!, request, conversion); + } + const entries = items.map((item, index) => + conversion.resolve({ + ...request, + logicalType: item, + path: `${request.path}[${index}]`, + depth: (request.depth ?? 0) + 1, + }) + ); + const childFailure = firstUnresolvedChild(entries); + if (childFailure) { + return childFailure; + } + const values = entries as SupportedValueResolution[]; + return { + status: 'supported', + value: { + kind: 'tuple', + wire: 'json', + decodedAs: 'array', + items: values.map(entry => entry.value), + }, + }; +} + +type WireRelation = 'disjoint' | 'same-decoding' | 'ambiguous'; + +function combineWireRelations(relations: readonly WireRelation[]): WireRelation { + if (relations.includes('ambiguous')) { + return 'ambiguous'; + } + return relations.includes('same-decoding') ? 'same-decoding' : 'disjoint'; +} + +type WireCategory = 'null' | 'boolean' | 'number' | 'string' | 'array' | 'object' | 'unknown'; + +function acceptsWireCategory(value: ValueContractV3, category: WireCategory): boolean { + if (category === 'unknown' || value.kind === 'unsupported') { + return true; + } + if (value.kind === 'union') { + return value.options.some(option => acceptsWireCategory(option, category)); + } + const expected: WireCategory = (() => { + switch (value.kind) { + case 'null': + return 'null'; + case 'boolean': + return 'boolean'; + case 'integer': + case 'float': + return 'number'; + case 'string': + return 'string'; + case 'sequence': + case 'tuple': + return 'array'; + case 'bytes': + case 'integer-exact': + case 'record': + case 'ndarray-float16': + case 'torch-float16': + return 'object'; + } + })(); + return expected === category; +} + +interface TaggedEnvelopeShape { + readonly required: Readonly>; + readonly optional?: Readonly>; +} + +function taggedEnvelopeShapes(value: ValueContractV3): readonly TaggedEnvelopeShape[] { + switch (value.kind) { + case 'integer-exact': + return [ + { + required: { + __tywrap__: 'string', + codecVersion: 'number', + encoding: 'string', + value: 'string', + }, + }, + ]; + case 'bytes': + return [ + { required: { __type__: 'string', encoding: 'string', data: 'string' } }, + { required: { __tywrap_bytes__: 'boolean', b64: 'string' } }, + ]; + case 'ndarray-float16': + // Legacy envelopes may omit the version, shape, and dtype. + return [ + { + required: { __tywrap__: 'string', encoding: 'string', b64: 'string' }, + optional: { codecVersion: 'number' }, + }, + { + required: { __tywrap__: 'string', encoding: 'string', data: 'unknown' }, + optional: { codecVersion: 'number' }, + }, + ]; + case 'torch-float16': + return [ + { + required: { __tywrap__: 'string', encoding: 'string', value: 'object' }, + optional: { + codecVersion: 'number', + device: 'string', + sourceDtype: 'string', + sourceDevice: 'string', + }, + }, + ]; + default: + return []; + } +} + +function recordCanMatchEnvelope( + record: Extract, + envelope: TaggedEnvelopeShape +): boolean { + const fields = new Map(record.fields.map(field => [field.name, field] as const)); + // Current decoders accept extra keys on marker envelopes. + for (const [name, category] of Object.entries(envelope.required)) { + const field = fields.get(name); + if (field && !acceptsWireCategory(field.value, category)) { + return false; + } + if (record.additionalValues && !acceptsWireCategory(record.additionalValues, category)) { + return false; + } + } + // An optional marker field proves disjointness only when the record requires it. + for (const [name, category] of Object.entries(envelope.optional ?? {})) { + const field = fields.get(name); + if (field?.required && !acceptsWireCategory(field.value, category)) { + return false; + } + if ( + field?.required && + record.additionalValues && + !acceptsWireCategory(record.additionalValues, category) + ) { + return false; + } + } + return true; +} + +function taggedRecordRelation( + record: Extract, + tagged: ValueContractV3 +): WireRelation { + return taggedEnvelopeShapes(tagged).some(envelope => recordCanMatchEnvelope(record, envelope)) + ? 'ambiguous' + : 'disjoint'; +} + +function recordWireRelation(left: ValueContractV3, right: ValueContractV3): WireRelation { + if (left.kind !== 'record' || right.kind !== 'record') { + return 'disjoint'; + } + const leftFields = new Map(left.fields.map(field => [field.name, field] as const)); + const rightFields = new Map(right.fields.map(field => [field.name, field] as const)); + const relations: WireRelation[] = []; + for (const field of left.fields) { + const otherField = rightFields.get(field.name); + const other = otherField?.value ?? right.additionalValues; + if (other) { + const relation = valueWireRelation(field.value, other); + if (relation === 'disjoint' && (field.required || otherField?.required)) { + return 'disjoint'; + } + relations.push(relation); + } + } + for (const field of right.fields) { + if (leftFields.has(field.name)) { + continue; + } + if (left.additionalValues) { + const relation = valueWireRelation(left.additionalValues, field.value); + if (relation === 'disjoint' && field.required) { + return 'disjoint'; + } + relations.push(relation); + } + } + if (left.additionalValues && right.additionalValues) { + relations.push(valueWireRelation(left.additionalValues, right.additionalValues)); + } + return relations.includes('ambiguous') ? 'ambiguous' : 'same-decoding'; +} + +function valueWireRelation(left: ValueContractV3, right: ValueContractV3): WireRelation { + if (left.kind === 'unsupported' || right.kind === 'unsupported') { + return 'ambiguous'; + } + if (left.kind === 'union') { + return combineWireRelations(left.options.map(option => valueWireRelation(option, right))); + } + if (right.kind === 'union') { + return combineWireRelations(right.options.map(option => valueWireRelation(left, option))); + } + if (left.kind === 'record' && right.kind === 'record') { + return recordWireRelation(left, right); + } + if (left.kind === 'record' && taggedEnvelopeShapes(right).length > 0) { + return taggedRecordRelation(left, right); + } + if (right.kind === 'record' && taggedEnvelopeShapes(left).length > 0) { + return taggedRecordRelation(right, left); + } + if (left.kind === 'sequence' && right.kind === 'sequence') { + return valueWireRelation(left.item, right.item) === 'ambiguous' ? 'ambiguous' : 'same-decoding'; + } + if (left.kind === 'tuple' && right.kind === 'tuple') { + if (left.items.length !== right.items.length) { + return 'disjoint'; + } + const relations = left.items.map((item, index) => valueWireRelation(item, right.items[index]!)); + return relations.includes('disjoint') ? 'disjoint' : combineWireRelations(relations); + } + if (left.kind === 'sequence' && right.kind === 'tuple') { + const relations = right.items.map(item => valueWireRelation(left.item, item)); + return relations.includes('disjoint') ? 'disjoint' : combineWireRelations(relations); + } + if (left.kind === 'tuple' && right.kind === 'sequence') { + return valueWireRelation(right, left); + } + if ( + (left.kind === 'integer' && right.kind === 'float') || + (left.kind === 'float' && right.kind === 'integer') + ) { + return 'same-decoding'; + } + return left.kind === right.kind ? 'same-decoding' : 'disjoint'; +} + +function resolveUnion( + options: readonly PythonType[], + request: ValueConversionRequest, + conversion: Pick +): ValueResolution { + if (options.length < 2 || options.length > 32) { + return { + status: 'unsupported', + reason: 'Revision 2 accepts unions with two to 32 alternatives.', + guidance: 'Split a larger union or provide an explicit tagged record adapter.', + }; + } + const entries = options.map((option, index) => + conversion.resolve({ + ...request, + logicalType: option, + path: `${request.path}.options[${index}]`, + depth: (request.depth ?? 0) + 1, + }) + ); + const childFailure = firstUnresolvedChild(entries); + if (childFailure) { + return childFailure; + } + const values = entries as SupportedValueResolution[]; + const first = values[0]?.value; + const second = values[1]?.value; + if (!first || !second) { + return { + status: 'unsupported', + reason: 'Revision 2 requires at least two supported union alternatives.', + guidance: 'Provide two explicit value alternatives.', + }; + } + const wireKinds = values.flatMap(entry => rootWireKinds(entry.value)); + if (wireKinds.includes('integer-exact') && wireKinds.includes('record')) { + return { + status: 'unsupported', + reason: 'An exact integer tag can overlap a record wire value.', + guidance: 'Use a disjoint tagged record instead of this union.', + }; + } + for (let index = 0; index < values.length; index += 1) { + for (let earlier = 0; earlier < index; earlier += 1) { + if (valueWireRelation(values[earlier]!.value, values[index]!.value) === 'ambiguous') { + return { + status: 'unsupported', + reason: 'Union alternatives can share a wire value but decode differently.', + guidance: 'Use a disjoint tagged record or split the union.', + }; + } + } + } + return { + status: 'supported', + value: { + kind: 'union', + wire: 'selected-option', + decodedAs: 'selected-option', + options: [first, second, ...values.slice(2).map(entry => entry.value)], + }, + }; +} + +function resolveNdarray(type: PythonType): ValueResolution { + const typeArgument = + type.kind === 'generic' && + type.typeArgs.length === 2 && + type.typeArgs[1]?.kind === 'generic' && + type.typeArgs[1].name === 'dtype' && + type.typeArgs[1].module === 'numpy' && + (type.typeArgs[0]?.kind === 'collection' || + (type.typeArgs[0]?.kind === 'custom' && type.typeArgs[0].name === 'Any')) + ? type.typeArgs[1].typeArgs[0] + : type.kind === 'generic' && type.typeArgs.length === 1 + ? type.typeArgs[0] + : undefined; + if ( + typeArgument?.kind !== 'custom' || + typeArgument.name !== 'float16' || + typeArgument.module !== 'numpy' + ) { + return { + status: 'unresolved', + annotation: annotationName(type), + }; + } + return { + status: 'supported', + value: { + kind: 'ndarray-float16', + wire: 'arrow', + decodedAs: 'nested-array-or-scalar', + element: { kind: 'float', wire: 'json', decodedAs: 'number', constraint: 'finite' }, + dtype: 'float16', + }, + }; +} + +function resolveTorchFloat16(): ValueResolution { + const ndarray = resolveNdarray({ + kind: 'generic', + name: 'ndarray', + module: 'numpy', + typeArgs: [{ kind: 'custom', name: 'float16', module: 'numpy' }], + }); + if (ndarray.status !== 'supported' || ndarray.value.kind !== 'ndarray-float16') { + return ndarray; + } + return { + status: 'supported', + value: { + kind: 'torch-float16', + wire: 'ndarray-envelope', + decodedAs: 'tensor-record', + dtype: 'torch.float16', + value: ndarray.value, + }, + }; +} + +function depthLimitResolution( + depth: number | undefined, + revision: ValueContractRevision +): UnsupportedValueResolution | null { + return (depth ?? 0) > 64 + ? { + status: 'unsupported', + reason: `Revision ${revision} limits value contracts to 64 nested nodes.`, + guidance: 'Flatten the value or provide a bounded adapter.', + } + : null; +} + +/** The conversion set that #335 may use with the frozen value-contract revision. */ +export const DEFAULT_VALUE_CONVERSION: ValueConversionDescription = { + revision: VALUE_CONTRACT_REVISION, + resolve(request): ValueResolution { + const { logicalType: type } = request; + const nestedConversion: Pick = { + resolve: request.resolveNested ?? DEFAULT_VALUE_CONVERSION.resolve, + }; + const depthFailure = depthLimitResolution(request.depth, VALUE_CONTRACT_REVISION); + if (depthFailure) { + return depthFailure; + } + switch (type.kind) { + case 'primitive': + if (type.name === 'None') { + return { status: 'supported', value: { kind: 'null', wire: 'json', decodedAs: 'null' } }; + } + if (type.name === 'bool') { + return { + status: 'supported', + value: { kind: 'boolean', wire: 'json', decodedAs: 'boolean' }, + }; + } + if (type.name === 'int') { + return { + status: 'supported', + value: { + kind: 'integer', + wire: 'json', + decodedAs: 'number', + constraint: 'safe-integer', + }, + }; + } + if (type.name === 'float') { + return { + status: 'supported', + value: { kind: 'float', wire: 'json', decodedAs: 'number', constraint: 'finite' }, + }; + } + if (type.name === 'str') { + return { + status: 'supported', + value: { kind: 'string', wire: 'json', decodedAs: 'string' }, + }; + } + if (type.name === 'bytes') { + return { + status: 'supported', + value: { kind: 'bytes', wire: 'base64-envelope', decodedAs: 'Uint8Array' }, + }; + } + return { + status: 'unsupported', + reason: 'The value contract does not specify this primitive conversion.', + guidance: 'Use a supported primitive or an explicit value adapter.', + }; + case 'annotated': + return nestedConversion.resolve({ ...request, logicalType: type.base }); + case 'final': + case 'classvar': + return nestedConversion.resolve({ ...request, logicalType: type.type }); + case 'optional': + return resolveUnion( + [type.type, { kind: 'primitive', name: 'None' }], + request, + nestedConversion + ); + case 'union': + return resolveUnion(type.types, request, nestedConversion); + case 'collection': + if (type.name === 'dict') { + const key = type.itemTypes[0]; + if (key?.kind !== 'primitive' || key.name !== 'str') { + return { + status: 'unsupported', + reason: 'The frozen record contract requires string keys.', + guidance: 'Convert keys to strings before crossing the value RPC boundary.', + }; + } + return resolveRecord(type.itemTypes[1] ?? UNKNOWN_TYPE, request, nestedConversion); + } + if (type.name === 'tuple') { + return resolveTuple(type.itemTypes, request, nestedConversion); + } + return resolveSequence(type.itemTypes[0] ?? UNKNOWN_TYPE, request, nestedConversion); + case 'generic': { + const leaf = leafName(type); + if (leaf === 'NDArray' || leaf === 'ndarray') { + return resolveNdarray(type); + } + if (leaf === 'Tensor' && type.module?.startsWith('torch')) { + const tensorDtype = type.typeArgs[0]; + if ( + type.typeArgs.length !== 1 || + tensorDtype?.kind !== 'custom' || + tensorDtype.name !== 'float16' || + tensorDtype.module !== 'torch' + ) { + return { status: 'unresolved', annotation: annotationName(type) }; + } + return resolveTorchFloat16(); + } + if (['list', 'List', 'Sequence', 'Iterable', 'set', 'frozenset'].includes(leaf ?? '')) { + return resolveSequence(type.typeArgs[0] ?? UNKNOWN_TYPE, request, nestedConversion); + } + if (['dict', 'Dict', 'Mapping', 'MutableMapping'].includes(leaf ?? '')) { + const key = type.typeArgs[0]; + if (key?.kind !== 'primitive' || key.name !== 'str') { + return { + status: 'unsupported', + reason: 'The frozen record contract requires string keys.', + guidance: 'Convert keys to strings before crossing the value RPC boundary.', + }; + } + return resolveRecord(type.typeArgs[1] ?? UNKNOWN_TYPE, request, nestedConversion); + } + return { status: 'unresolved', annotation: annotationName(type) }; + } + case 'custom': { + const leaf = leafName(type); + if (type.name === 'HalfTensor' && type.module === 'torch') { + return resolveTorchFloat16(); + } + if (leaf === 'ndarray' || leaf === 'NDArray') { + return resolveNdarray(type); + } + return { status: 'unresolved', annotation: annotationName(type) }; + } + default: + return { status: 'unresolved', annotation: annotationName(type) }; + } + }, +}; + +/** Explicit revision-3 mode uses the revision-2 rules for every other value. */ +export const EXACT_INTEGER_VALUE_CONVERSION: ValueConversionDescription = { + revision: VALUE_CONTRACT_V3_REVISION, + resolve(request): ValueResolution { + const depthFailure = depthLimitResolution(request.depth, VALUE_CONTRACT_V3_REVISION); + if (depthFailure) { + return depthFailure; + } + if (request.logicalType.kind === 'primitive' && request.logicalType.name === 'int') { + return { + status: 'supported', + value: { + kind: 'integer-exact', + wire: 'decimal-string-envelope', + decodedAs: 'bigint', + constraint: 'exact-integer', + }, + }; + } + return DEFAULT_VALUE_CONVERSION.resolve({ + ...request, + resolveNested: request.resolveNested ?? EXACT_INTEGER_VALUE_CONVERSION.resolve, + }); + }, +}; + +function capabilityNamesFor(value: ValueContractV3): CallableCapability[] { + const names = new Set(['value-rpc', 'return-validation']); + const collect = (current: ValueContractV3): void => { + switch (current.kind) { + case 'integer-exact': + names.add('exact-integer-adapter'); + break; + case 'sequence': + collect(current.item); + break; + case 'tuple': + current.items.forEach(collect); + break; + case 'union': + current.options.forEach(collect); + break; + case 'record': + current.fields.forEach(field => collect(field.value)); + if (current.additionalValues) { + collect(current.additionalValues); + } + break; + case 'ndarray-float16': + names.add('scientific-ndarray'); + break; + case 'torch-float16': + names.add('scientific-torch'); + names.add('scientific-ndarray'); + break; + } + }; + collect(value); + return [...names]; +} + +function containsNamedType(type: PythonType, names: ReadonlySet): boolean { + if ((type.kind === 'custom' || type.kind === 'generic') && names.has(leafName(type) ?? '')) { + return true; + } + switch (type.kind) { + case 'collection': + return type.itemTypes.some(item => containsNamedType(item, names)); + case 'union': + return type.types.some(item => containsNamedType(item, names)); + case 'optional': + case 'final': + case 'classvar': + case 'unpack': + return containsNamedType(type.type, names); + case 'annotated': + return containsNamedType(type.base, names); + case 'generic': + return type.typeArgs.some(item => containsNamedType(item, names)); + case 'callable': + return ( + type.parameters.some(item => containsNamedType(item, names)) || + containsNamedType(type.returnType, names) + ); + default: + return false; + } +} + +function diagnosticForResolution( + resolution: ValueResolution, + path: string +): CallableCompilationDiagnostic | null { + if (resolution.status === 'supported') { + return null; + } + if (resolution.status === 'unresolved') { + return { + severity: 'warning', + code: 'conversion-unresolved', + path, + message: `${path}: no value conversion is defined for ${resolution.annotation}; the generated result type is unknown.`, + }; + } + return { + severity: 'error', + code: 'conversion-unsupported', + path, + message: `${path}: ${resolution.reason} ${resolution.guidance}`, + }; +} + +function outputType(value: ResolvedCallableValue): PythonType { + return value.resolution.status === 'supported' ? value.logicalType : UNKNOWN_TYPE; +} + +function valuesMayOverlap(left: ValueContractV3, right: ValueContractV3): boolean { + if (left.kind === 'unsupported' || right.kind === 'unsupported') { + return true; + } + if (left.kind === 'union') { + return left.options.some(option => valuesMayOverlap(option, right)); + } + if (right.kind === 'union') { + return right.options.some(option => valuesMayOverlap(left, option)); + } + if ( + (left.kind === 'integer' && right.kind === 'float') || + (left.kind === 'float' && right.kind === 'integer') + ) { + return true; + } + if ( + left.kind === 'ndarray-float16' || + right.kind === 'ndarray-float16' || + left.kind === 'torch-float16' || + right.kind === 'torch-float16' + ) { + return true; + } + if (left.kind === 'tuple' && right.kind === 'sequence') { + return left.items.every(item => valuesMayOverlap(item, right.item)); + } + if (left.kind === 'sequence' && right.kind === 'tuple') { + return right.items.every(item => valuesMayOverlap(left.item, item)); + } + if (left.kind !== right.kind) { + return false; + } + if (left.kind === 'tuple' && right.kind === 'tuple') { + return ( + left.items.length === right.items.length && + left.items.every((item, index) => valuesMayOverlap(item, right.items[index]!)) + ); + } + if (left.kind === 'sequence' && right.kind === 'sequence') { + return true; // An empty array matches both element schemas. + } + return true; +} + +function positionalSlot(parameters: readonly Parameter[], index: number): number | null { + const parameter = parameters[index]!; + if (parameter.keywordOnly || parameter.kwArgs || parameter.varArgs) { + return null; + } + let slot = 0; + for (const earlier of parameters.slice(0, index)) { + if (earlier.varArgs) { + return null; + } + if (!earlier.keywordOnly && !earlier.kwArgs) { + slot += 1; + } + } + return slot; +} + +function sharesRequiredBinding( + left: readonly Parameter[], + leftIndex: number, + right: readonly Parameter[], + rightIndex: number +): boolean { + const a = left[leftIndex]!; + const b = right[rightIndex]!; + if ( + a.optional || + b.optional || + a.varArgs || + b.varArgs || + a.kwArgs || + b.kwArgs || + a.name !== b.name + ) { + return false; + } + if (a.keywordOnly && b.keywordOnly) { + return true; + } + if (a.keywordOnly || b.keywordOnly) { + return !a.positionalOnly && !b.positionalOnly; + } + const leftSlot = positionalSlot(left, leftIndex); + return leftSlot !== null && leftSlot === positionalSlot(right, rightIndex); +} + +function overloadsMayOverlap( + left: readonly ResolvedCallableValue[], + right: readonly ResolvedCallableValue[], + leftParameters: readonly Parameter[], + rightParameters: readonly Parameter[] +): boolean { + const countRange = (parameters: readonly Parameter[]): [number, number] => [ + parameters.filter(parameter => !parameter.optional && !parameter.varArgs && !parameter.kwArgs) + .length, + parameters.some(parameter => parameter.varArgs || parameter.kwArgs) + ? Number.POSITIVE_INFINITY + : parameters.length, + ]; + const [leftMin, leftMax] = countRange(leftParameters); + const [rightMin, rightMax] = countRange(rightParameters); + if (leftMax < rightMin || rightMax < leftMin) { + return false; + } + for (let leftIndex = 0; leftIndex < leftParameters.length; leftIndex += 1) { + if ( + leftParameters.filter(parameter => parameter.name === leftParameters[leftIndex]!.name) + .length !== 1 + ) { + continue; + } + const rightIndex = rightParameters.findIndex( + parameter => parameter.name === leftParameters[leftIndex]!.name + ); + if ( + rightIndex < 0 || + rightParameters.filter(parameter => parameter.name === leftParameters[leftIndex]!.name) + .length !== 1 || + !sharesRequiredBinding(leftParameters, leftIndex, rightParameters, rightIndex) + ) { + continue; + } + const a = left[leftIndex]?.resolution; + const b = right[rightIndex]?.resolution; + if ( + a?.status === 'supported' && + b?.status === 'supported' && + !valuesMayOverlap(a.value, b.value) + ) { + return false; + } + } + return true; +} + +function resolveCallable( + func: PythonFunction, + path: string, + conversion: ValueConversionDescription, + capabilities: ReadonlyMap, + dataclassNames: ReadonlySet, + diagnostics: CallableCompilationDiagnostic[] +): { function: PythonFunction; callable: ResolvedCallable } { + const resolveValue = ( + direction: CallableDirection, + logicalType: PythonType, + valuePath: string + ): ResolvedCallableValue => ({ + direction, + path: valuePath, + logicalType, + resolution: conversion.resolve({ direction, logicalType, path: valuePath }), + }); + const parameters = func.parameters.map((parameter, index) => + resolveValue('input', parameter.type, `${path}.parameters[${index}]`) + ); + const result = resolveValue('output', func.returnType, `${path}.returns`); + const overloadParameters = (func.overloads ?? []).map((overload, overloadIndex) => + overload.parameters.map((parameter, parameterIndex) => + resolveValue( + 'input', + parameter.type, + `${path}.overloads[${overloadIndex}].parameters[${parameterIndex}]` + ) + ) + ); + const overloadResults = (func.overloads ?? []).map((overload, index) => + resolveValue('output', overload.returnType, `${path}.overloads[${index}].returns`) + ); + // Python binds these receivers before the wrapper sends RPC arguments. + const visibleParameters = parameters.filter( + (_, index) => func.parameters[index]?.name !== 'self' && func.parameters[index]?.name !== 'cls' + ); + const visibleOverloadParameters = overloadParameters.map((values, overloadIndex) => + values.filter( + (_, index) => + func.overloads?.[overloadIndex]?.parameters[index]?.name !== 'self' && + func.overloads?.[overloadIndex]?.parameters[index]?.name !== 'cls' + ) + ); + const visibleOverloadSignatures = (func.overloads ?? []).map(overload => + overload.parameters.filter(parameter => parameter.name !== 'self' && parameter.name !== 'cls') + ); + const values = [ + ...visibleParameters, + result, + ...visibleOverloadParameters.flat(), + ...overloadResults, + ]; + const rejectMixedExactKwargs = ( + source: readonly Parameter[], + resolved: readonly ResolvedCallableValue[], + sourcePath: string + ): void => { + if (!source.some(parameter => parameter.keywordOnly)) { + return; + } + const index = source.findIndex(parameter => parameter.kwArgs); + const resolution = resolved[index]?.resolution; + if ( + index >= 0 && + resolution?.status === 'supported' && + containsExactInteger(resolution.value) + ) { + throw new Error( + `${sourcePath}.parameters[${index}]: exact **kwargs cannot share a signature with named keyword-only parameters.` + ); + } + }; + rejectMixedExactKwargs(func.parameters, parameters, path); + (func.overloads ?? []).forEach((overload, index) => + rejectMixedExactKwargs( + overload.parameters, + overloadParameters[index] ?? [], + `${path}.overloads[${index}]` + ) + ); + const requiredCapabilities = new Set(); + for (const value of values) { + if (value.resolution.status === 'supported' && containsExactInteger(value.resolution.value)) { + if (conversion.revision !== VALUE_CONTRACT_V3_REVISION) { + throw new Error(`${value.path}: exact integers require value contract revision 3.`); + } + if (capabilities.get('exact-integer-adapter')?.available !== true) { + throw new Error(`${value.path}: exact-integer-adapter is unavailable.`); + } + } + const diagnostic = diagnosticForResolution(value.resolution, value.path); + if (diagnostic) { + diagnostics.push(diagnostic); + } + } + for (let index = 0; index < overloadParameters.length; index += 1) { + for (let earlier = 0; earlier < index; earlier += 1) { + if ( + overloadsMayOverlap( + visibleOverloadParameters[earlier]!, + visibleOverloadParameters[index]!, + visibleOverloadSignatures[earlier]!, + visibleOverloadSignatures[index]! + ) + ) { + diagnostics.push({ + severity: 'warning', + code: 'overload-ambiguous', + path: `${path}.overloads[${index}]`, + message: `${path}.overloads[${index}]: input values may also match overload ${earlier}. Runtime return validation selects the first declared match.`, + }); + } + } + } + for (const value of values) { + const directDataclass = + (value.logicalType.kind === 'custom' || value.logicalType.kind === 'generic') && + dataclassNames.has(leafName(value.logicalType) ?? ''); + const adaptedDataclass = + value.direction === 'output' && + directDataclass && + capabilities.get('dataclass-adapter')?.available === true && + value.resolution.status === 'supported' && + value.resolution.value.kind === 'record'; + if (adaptedDataclass) { + requiredCapabilities.add('dataclass-adapter'); + } else if (containsNamedType(value.logicalType, dataclassNames)) { + diagnostics.push({ + severity: 'error', + code: 'dataclass-unsupported', + path: value.path, + message: `${value.path}: a dataclass annotation has no value adapter. Use a TypedDict or an explicit record adapter until #339.`, + }); + value.resolution = { + status: 'unsupported', + reason: 'No dataclass value adapter is available.', + guidance: 'Use a TypedDict or an explicit record adapter.', + }; + } + if (value.direction === 'output' && func.isAsync) { + if (capabilities.get('coroutine-execution')?.available !== true) { + diagnostics.push({ + severity: 'error', + code: 'coroutine-unsupported', + path: value.path, + message: `${value.path}: this callable requires a runtime bridge that awaits Python coroutine results.`, + }); + value.resolution = { + status: 'unsupported', + reason: 'Coroutine execution is unavailable.', + guidance: 'Use a coroutine-capable runtime bridge or a synchronous adapter.', + }; + } else { + requiredCapabilities.add('coroutine-execution'); + } + } + if (value.resolution.status === 'supported') { + const needed = capabilityNamesFor(value.resolution.value); + needed.forEach(capability => requiredCapabilities.add(capability)); + const missing = needed.filter(capability => capabilities.get(capability)?.available !== true); + if (missing.length > 0) { + missing.forEach(capability => { + const description = capabilities.get(capability); + diagnostics.push({ + severity: 'error', + code: 'capability-unavailable', + path: value.path, + message: `${value.path}: ${capability} is required. ${description?.guidance ?? 'Add a declared capability before generating this callable.'}`, + }); + }); + value.resolution = { + status: 'unsupported', + reason: `Required capability is unavailable: ${missing.join(', ')}.`, + guidance: 'Provide the capability or use a supported value adapter.', + }; + } + } + } + + const resolvedParameters: Parameter[] = parameters.map((parameter, index) => ({ + ...func.parameters[index]!, + type: parameter.resolution.status === 'unsupported' ? UNKNOWN_TYPE : parameter.logicalType, + })); + const resolvedOverloads = (func.overloads ?? []).map((overload, index) => ({ + ...overload, + parameters: overload.parameters.map((parameter, parameterIndex) => ({ + ...parameter, + type: + overloadParameters[index]?.[parameterIndex]?.resolution.status === 'unsupported' + ? UNKNOWN_TYPE + : parameter.type, + })), + returnType: overloadResults[index] ? outputType(overloadResults[index]) : overload.returnType, + })); + const supportedValue = (value: ResolvedCallableValue): ValueContractV3 | undefined => + value.resolution.status === 'supported' ? value.resolution.value : undefined; + const resolvedFunction: PythonFunction = { + ...func, + parameters: resolvedParameters, + signature: { + ...func.signature, + parameters: resolvedParameters, + returnType: outputType(result), + }, + returnType: outputType(result), + overloads: resolvedOverloads, + callableContract: { + parameterValues: parameters.map(supportedValue), + returnValue: supportedValue(result), + returnValidationType: result.resolution.status === 'unresolved' ? func.returnType : undefined, + overloads: overloadResults.map((overload, index) => ({ + parameterValues: overloadParameters[index]!.map(supportedValue), + returnValue: supportedValue(overload), + returnValidationType: + overload.resolution.status === 'unresolved' + ? func.overloads![index]!.returnType + : undefined, + })), + }, + }; + return { + function: resolvedFunction, + callable: { + name: func.name, + path, + parameters, + result, + overloadParameters, + overloadResults, + requiredCapabilities: [...requiredCapabilities].sort(), + }, + }; +} + +/** + * Compile already-validated IR without filesystem, subprocess, cache, or + * registry access. `generate()` selects exports and writes these files. + */ +export function compileContract( + ir: ValidatedIrContract, + options: CompileContractOptions +): CompiledContract { + if ( + options.conversion.revision !== VALUE_CONTRACT_REVISION && + options.conversion.revision !== VALUE_CONTRACT_V3_REVISION + ) { + throw new Error(`Unsupported value contract revision ${options.conversion.revision}.`); + } + if (ir.module !== options.module.name) { + throw new Error( + `Compiled module ${options.module.name} does not match IR module ${ir.module}.` + ); + } + const canonical = transformIrToTsModel(ir); + const select = ( + kind: string, + source: readonly T[], + requested: readonly { name: string }[] + ): T[] => { + const byName = new Map(source.map(item => [item.name, item] as const)); + const seen = new Set(); + return requested.map(item => { + const match = byName.get(item.name); + if (!match || seen.has(item.name)) { + throw new Error(`Selected ${kind} ${item.name} does not match validated IR.`); + } + seen.add(item.name); + return match; + }); + }; + const selectedFunctions = select('function', canonical.functions, options.module.functions); + const selectedClasses = select('class', canonical.classes, options.module.classes); + const selectedAliases = select( + 'type alias', + canonical.typeAliases ?? [], + options.module.typeAliases ?? canonical.typeAliases ?? [] + ); + const localTypedDicts = new Map( + selectedClasses + .filter(cls => cls.kind === 'typed_dict' && !cls.typeParameters?.length) + .map(cls => [cls.name, cls] as const) + ); + const localAliases = new Map( + selectedAliases + .filter(alias => !alias.typeParameters?.length) + .map(alias => [alias.name, alias] as const) + ); + const conversion: ValueConversionDescription = { + revision: options.conversion.revision, + resolve(request): ValueResolution { + const type = request.logicalType; + const direct = options.conversion.resolve({ ...request, resolveNested: conversion.resolve }); + if ( + direct.status !== 'unresolved' || + type.kind !== 'custom' || + (type.module !== undefined && type.module !== ir.module) + ) { + return direct; + } + const typedDict = localTypedDicts.get(type.name); + if (typedDict) { + const key = `typed-dict:${type.name}`; + if (request.activeNames?.includes(key)) { + return { status: 'unresolved', annotation: annotationName(type) }; + } + if ((request.depth ?? 0) >= 64) { + return { + status: 'unsupported', + reason: `Revision ${conversion.revision} limits value contracts to 64 nested nodes.`, + guidance: 'Flatten the value or provide a bounded adapter.', + }; + } + const fields: ValueContractField[] = []; + for (const property of typedDict.properties) { + const field = conversion.resolve({ + ...request, + logicalType: property.type, + path: `${request.path}.${property.name}`, + depth: (request.depth ?? 0) + 1, + activeNames: [...(request.activeNames ?? []), key], + }); + if (field.status !== 'supported') { + return field; + } + fields.push({ name: property.name, value: field.value, required: !property.optional }); + } + return { + status: 'supported', + value: { kind: 'record', wire: 'json', decodedAs: 'object', fields }, + }; + } + const alias = localAliases.get(type.name); + if (alias) { + const key = `alias:${type.name}`; + if (request.activeNames?.includes(key)) { + return { status: 'unresolved', annotation: annotationName(type) }; + } + if ((request.depth ?? 0) >= 64) { + return { + status: 'unsupported', + reason: `Revision ${conversion.revision} limits value contracts to 64 nested nodes.`, + guidance: 'Flatten the value or provide a bounded adapter.', + }; + } + return conversion.resolve({ + ...request, + logicalType: alias.type, + depth: (request.depth ?? 0) + 1, + activeNames: [...(request.activeNames ?? []), key], + }); + } + return direct; + }, + }; + const capabilities = new Map( + options.capabilities.map(capability => [capability.name, capability]) + ); + const dataclassNames = new Set(ir.classes.filter(cls => cls.is_dataclass).map(cls => cls.name)); + const diagnostics: CallableCompilationDiagnostic[] = []; + const callables: ResolvedCallable[] = []; + const compileFunction = (func: PythonFunction, path: string): PythonFunction => { + const result = resolveCallable( + func, + path, + conversion, + capabilities, + dataclassNames, + diagnostics + ); + callables.push(result.callable); + return result.function; + }; + const module: PythonModule = { + ...canonical, + functions: selectedFunctions.map(func => + compileFunction( + func, + `$.functions[${ir.functions.findIndex(entry => entry.name === func.name)}]` + ) + ), + classes: selectedClasses.map(cls => ({ + ...cls, + methods: + cls.kind === 'protocol' + ? cls.methods + : cls.methods.map(method => { + const sourceClassIndex = ir.classes.findIndex(entry => entry.name === cls.name); + const sourceMethodIndex = ir.classes[sourceClassIndex]!.methods.findIndex( + entry => entry.name === method.name + ); + return compileFunction( + method, + `$.classes[${sourceClassIndex}].methods[${sourceMethodIndex}]` + ); + }), + })), + typeAliases: selectedAliases, + }; + const generated = options.generator.generateModuleDefinition(module, options.annotatedJSDoc); + return { + ir: { ir_version: ir.ir_version, module: ir.module }, + module, + callables, + diagnostics, + files: [ + { kind: 'typescript', content: generated.typescript }, + { kind: 'declaration', content: generated.declaration }, + ], + generated, + }; +} diff --git a/src/core/client-binding-prototype.ts b/src/core/client-binding-prototype.ts new file mode 100644 index 00000000..13fa4286 --- /dev/null +++ b/src/core/client-binding-prototype.ts @@ -0,0 +1,334 @@ +/** Opt-in generated client binding for the issue #340 prototype. */ + +import ts from 'typescript'; + +import type { GeneratedCode, PythonModule } from '../types/index.js'; +import type { CodeGenerator } from './generator.js'; + +export interface BindingPrototypeCode extends GeneratedCode { + bindingPrototype: { + core: Pick; + client: Pick; + }; +} + +interface ClassExport { + name: string; + methods: string[]; +} + +interface ExportedCalls { + functions: string[]; + classes: ClassExport[]; + typeAliases: string[]; +} + +function quotedProperty(name: string): string { + return `[${JSON.stringify(name)}]`; +} + +function allocateName(base: string, used: ReadonlySet): string { + let name = base; + let suffix = 2; + while (used.has(name)) { + name = `${base}${suffix++}`; + } + return name; +} + +function stripExport( + source: ts.SourceFile, + node: ts.FunctionDeclaration | ts.ClassDeclaration +): string { + const start = node.getFullStart(); + const end = node.getEnd(); + let text = source.text.slice(start, end); + const exportModifier = node.modifiers?.find( + modifier => modifier.kind === ts.SyntaxKind.ExportKeyword + ); + if (exportModifier) { + const from = exportModifier.getStart(source) - start; + const to = exportModifier.getEnd() - start; + text = `${text.slice(0, from)}${text.slice(to).replace(/^\s/, '')}`; + } + return text; +} + +function inspectExports(source: ts.SourceFile): ExportedCalls { + const functions: string[] = []; + const classes: ClassExport[] = []; + const typeAliases: string[] = []; + for (const node of source.statements) { + if (ts.isFunctionDeclaration(node) && node.body && node.name) { + functions.push(node.name.text); + } else if (ts.isClassDeclaration(node) && node.name) { + const methods = node.members + .filter( + (member): member is ts.MethodDeclaration => + ts.isMethodDeclaration(member) && + member.body !== undefined && + member.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.StaticKeyword) === + true + ) + .map(member => { + if (!ts.isIdentifier(member.name)) { + throw new Error(`Cannot bind computed method in ${node.name?.text}`); + } + return member.name.text; + }); + classes.push({ name: node.name.text, methods }); + } else if ( + ts.isTypeAliasDeclaration(node) && + node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword) + ) { + typeAliases.push(node.name.text); + } + } + const names = [...functions, ...classes.map(cls => cls.name), ...typeAliases]; + if (new Set(names).size !== names.length) { + throw new Error('Generated module has duplicate exported names'); + } + return { functions, classes, typeAliases }; +} + +function countCalls(source: ts.SourceFile, identifier: string): number { + let count = 0; + const visit = (node: ts.Node): void => { + if ( + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === identifier + ) { + count++; + } + ts.forEachChild(node, visit); + }; + visit(source); + return count; +} + +function functionKeyUnion(names: readonly string[]): string { + return names.length > 0 ? names.map(name => JSON.stringify(name)).join(' | ') : 'never'; +} + +function renderClient( + moduleName: string, + coreFactory: string, + calls: ExportedCalls +): Pick { + const coreFile = `./${moduleName}.generated.core.js`; + const functionFields = calls.functions.map( + name => ` ${quotedProperty(name)}: core${quotedProperty(name)},` + ); + const classFields = calls.classes + .filter(cls => cls.methods.length > 0) + .map( + cls => + ` ${quotedProperty(cls.name)}: { ${cls.methods + .map( + method => + `${quotedProperty(method)}: core${quotedProperty(cls.name)}${quotedProperty(method)}` + ) + .join(', ')} },` + ); + const classTypes = calls.classes + .filter(cls => cls.methods.length > 0) + .map( + cls => + ` ${quotedProperty(cls.name)}: Pick<__CoreApi[${JSON.stringify(cls.name)}], ${functionKeyUnion(cls.methods)}>;` + ) + .join('\n'); + const types = `export type BoundRuntime = Pick, 'call'>; +type __CoreApi = ReturnType; +export type BoundApi = Pick<__CoreApi, ${functionKeyUnion(calls.functions)}> & { +${classTypes} +}; +export interface BoundHandle { + api: BoundApi; + dispose(): void; +}`; + const typescript = `// Generated by tywrap: explicit runtime binding prototype +import { ${coreFactory} } from '${coreFile}'; +import { BridgeDisposedError } from 'tywrap'; + +${types} + +export function bindRuntime(runtime: BoundRuntime): BoundHandle { + let disposed = false; + const core = ${coreFactory}(() => { + if (disposed) throw new BridgeDisposedError('Bound client has been disposed'); + return runtime; + }); + const api: BoundApi = { +${[...functionFields, ...classFields].join('\n')} + }; + return { + api, + dispose(): void { disposed = true; }, + }; +} +`; + const declaration = `// Generated by tywrap: explicit runtime binding prototype +import { ${coreFactory} } from '${coreFile}'; + +${types} + +export declare function bindRuntime(runtime: BoundRuntime): BoundHandle; +`; + return { typescript, declaration }; +} + +/** + * Split one compiled wrapper into a shared core and two call providers. + * This function does not change the default generator output. + */ +export function renderClientBindingPrototype( + module: PythonModule, + generator: Pick, + annotatedJSDoc = false, + runtimeGetterIdentifier = '__tywrapRuntimeProvider' +): BindingPrototypeCode { + const moduleName = module.name; + if (!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/.test(moduleName)) { + throw new Error(`Invalid Python module name: ${moduleName}`); + } + if (!/^__tywrapRuntimeProvider(?:[1-9][0-9]*)?$/.test(runtimeGetterIdentifier)) { + throw new Error(`Invalid runtime getter identifier: ${runtimeGetterIdentifier}`); + } + const generated = generator.generateModuleDefinition(module, annotatedJSDoc); + const bindingTemplate = generator.generateModuleBindingTemplate( + module, + annotatedJSDoc, + runtimeGetterIdentifier + ); + if (generated.sourceMap !== undefined || bindingTemplate.sourceMap !== undefined) { + throw new Error('Client binding prototype does not support source maps'); + } + const source = ts.createSourceFile( + `${moduleName}.generated.ts`, + bindingTemplate.typescript, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS + ); + const declarations = ts.createSourceFile( + `${moduleName}.generated.d.ts`, + bindingTemplate.declaration, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS + ); + const calls = inspectExports(source); + const callableCount = + calls.functions.length + calls.classes.reduce((count, cls) => count + cls.methods.length, 0); + if ( + countCalls(source, runtimeGetterIdentifier) !== callableCount || + countCalls(source, 'getRuntimeBridge') !== 0 || + bindingTemplate.declaration !== generated.declaration + ) { + throw new Error('Binding template call sites or declarations differ from default output'); + } + const usedNames = new Set([ + ...calls.functions, + ...calls.classes.map(cls => cls.name), + ...calls.typeAliases, + ]); + const coreFactory = allocateName('__tywrapCreateApi', usedNames); + usedNames.add(coreFactory); + const legacyValue = allocateName('__tywrapLegacy', usedNames); + usedNames.add(legacyValue); + const registryImport = allocateName('__tywrapRegistry', usedNames); + usedNames.add(registryImport); + const providerName = runtimeGetterIdentifier; + if (usedNames.has(providerName)) { + throw new Error(`Generated module defines reserved provider name ${providerName}`); + } + usedNames.add(providerName); + const runtimeType = allocateName('__TywrapRuntime', usedNames); + const imports: string[] = []; + const typeAliases: string[] = []; + const body: string[] = []; + for (const node of source.statements) { + if (ts.isImportDeclaration(node)) { + imports.push(node.getText(source)); + } else if (ts.isTypeAliasDeclaration(node)) { + typeAliases.push(node.getText(source)); + } else if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) { + body.push(stripExport(source, node)); + } else { + body.push(node.getFullText(source)); + } + } + const returned = [...calls.functions, ...calls.classes.map(cls => cls.name)] + .map(name => `${quotedProperty(name)}: ${name}`) + .join(', '); + const coreTypescript = `// Generated by tywrap: shared call implementation +${imports.join('\n')} +${typeAliases.join('\n')} + +type ${runtimeType} = Pick, 'call'>; +export function ${coreFactory}(${providerName}: () => ${runtimeType}) { +${body.join('\n')} + return { ${returned} }; +} +`; + const coreSource = ts.createSourceFile( + `${moduleName}.generated.core.ts`, + coreTypescript, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS + ); + if ( + countCalls(coreSource, providerName) !== callableCount || + countCalls(coreSource, 'getRuntimeBridge') !== 0 + ) { + throw new Error('Generated core did not bind every call site'); + } + const declarationBodies = declarations.statements + .filter( + (node): node is ts.FunctionDeclaration | ts.ClassDeclaration => + ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) + ) + .map(node => stripExport(declarations, node)) + .join('\n'); + const returnedTypes = [...calls.functions, ...calls.classes.map(cls => cls.name)] + .map(name => ` ${quotedProperty(name)}: typeof ${name};`) + .join('\n'); + const coreDeclaration = `// Generated by tywrap: shared call implementation +${typeAliases.join('\n')} +type ${runtimeType} = Pick, 'call'>; +${declarationBodies} +export declare function ${coreFactory}(${providerName}: () => ${runtimeType}): { +${returnedTypes} +}; +`; + const coreFile = `./${moduleName}.generated.core.js`; + const legacyFunctions = calls.functions.map( + name => `export const ${name} = ${legacyValue}${quotedProperty(name)};` + ); + const legacyClasses = calls.classes.flatMap(cls => [ + `export const ${cls.name} = ${legacyValue}${quotedProperty(cls.name)};`, + `export type ${cls.name} = InstanceType;`, + ]); + const legacyTypes = + calls.typeAliases.length > 0 + ? `export type { ${calls.typeAliases.join(', ')} } from '${coreFile}';\n` + : ''; + const legacyTypescript = `// Generated by tywrap: registry-backed wrapper prototype +import { ${coreFactory} } from '${coreFile}'; +import { getRuntimeBridge as ${registryImport} } from 'tywrap/runtime'; +${legacyTypes} +const ${legacyValue} = ${coreFactory}(${registryImport}); +${[...legacyFunctions, ...legacyClasses].join('\n')} +`; + return { + ...generated, + typescript: legacyTypescript, + declaration: generated.declaration, + bindingPrototype: { + core: { typescript: coreTypescript, declaration: coreDeclaration }, + client: renderClient(moduleName, coreFactory, calls), + }, + }; +} diff --git a/src/core/generator.ts b/src/core/generator.ts index 899fa6a1..5b1d6912 100644 --- a/src/core/generator.ts +++ b/src/core/generator.ts @@ -9,9 +9,12 @@ import type { PythonModule, PythonType, PythonTypeAlias, + Parameter, GeneratedCode, TypescriptType, } from '../types/index.js'; +import { containsExactInteger, type ValueContractV3 } from '../contracts/value-contract.js'; +import type { OverloadReturnSchema, ReturnSchema } from '../runtime/validators.js'; import { globalCache } from '../utils/cache.js'; import { @@ -36,7 +39,122 @@ interface GenericRenderContext { emittedParamSpecs: Set; } -type ReturnDefinitionNames = ReadonlySet; +type ReturnDefinitionNames = ReadonlySet & { readonly moduleName?: string }; + +function valueContractToReturnSchema(value: ValueContractV3): ReturnSchema { + switch (value.kind) { + case 'null': + return { kind: 'primitive', type: 'null' }; + case 'boolean': + return { kind: 'primitive', type: 'boolean' }; + case 'integer': + return { kind: 'primitive', type: 'number', constraint: value.constraint }; + case 'integer-exact': + return { kind: 'primitive', type: 'bigint' }; + case 'float': + return { kind: 'primitive', type: 'number', constraint: value.constraint }; + case 'string': + return { kind: 'primitive', type: 'string' }; + case 'bytes': + return { kind: 'primitive', type: 'Uint8Array' }; + case 'sequence': + return { kind: 'array', element: valueContractToReturnSchema(value.item) }; + case 'tuple': + return { kind: 'tuple', elements: value.items.map(valueContractToReturnSchema) }; + case 'union': + return { kind: 'union', options: value.options.map(valueContractToReturnSchema) }; + case 'record': + return { + kind: 'record', + fields: Object.fromEntries( + value.fields.map(field => [ + field.name, + { schema: valueContractToReturnSchema(field.value), optional: !field.required }, + ]) + ), + values: value.additionalValues + ? valueContractToReturnSchema(value.additionalValues) + : undefined, + }; + case 'ndarray-float16': + return { kind: 'marker', marker: 'ndarray', dtype: value.dtype, dims: value.rank }; + case 'torch-float16': + return { kind: 'marker', marker: 'torch.tensor', dtype: value.dtype }; + case 'unsupported': + return { kind: 'any' }; + } +} + +function valueContractToTsType(value: ValueContractV3): string { + switch (value.kind) { + case 'null': + return 'null'; + case 'boolean': + return 'boolean'; + case 'integer': + case 'float': + return 'number'; + case 'integer-exact': + return 'bigint'; + case 'string': + return 'string'; + case 'bytes': + return 'Uint8Array'; + case 'sequence': { + const item = valueContractToTsType(value.item); + return `${value.item.kind === 'union' ? `(${item})` : item}[]`; + } + case 'tuple': + return `[${value.items.map(valueContractToTsType).join(', ')}]`; + case 'union': + return value.options.map(valueContractToTsType).join(' | '); + case 'record': { + const fields = value.fields + .map( + field => + `${JSON.stringify(field.name)}${field.required ? '' : '?'}: ${valueContractToTsType(field.value)};` + ) + .join(' '); + const record = `{ ${fields} }`; + if (!value.additionalValues) { + return record; + } + const additional = `Record`; + return value.fields.length === 0 ? additional : `(${record} & ${additional})`; + } + case 'ndarray-float16': + return '__tywrapFloat16Value'; + case 'torch-float16': + return '__tywrapFloat16Tensor'; + case 'unsupported': + return 'unknown'; + } +} + +function containsScientificValue( + value: ValueContractV3, + kind: 'ndarray-float16' | 'torch-float16' +): boolean { + if (value.kind === kind) { + return true; + } + switch (value.kind) { + case 'sequence': + return containsScientificValue(value.item, kind); + case 'tuple': + return value.items.some(item => containsScientificValue(item, kind)); + case 'union': + return value.options.some(option => containsScientificValue(option, kind)); + case 'record': + return ( + value.fields.some(field => containsScientificValue(field.value, kind)) || + (value.additionalValues !== undefined && + containsScientificValue(value.additionalValues, kind)) + ); + default: + return false; + } +} export interface CodeGeneratorOptions { /** Reports a generated annotation that cannot be represented by emitted declarations. */ @@ -101,6 +219,60 @@ export class CodeGenerator { this.onTypeDegrade = options.onTypeDegrade; } + private assertRuntimeGetterIdentifier(identifier: string): void { + if ( + identifier !== 'getRuntimeBridge' && + !/^__tywrapRuntimeProvider(?:[1-9][0-9]*)?$/.test(identifier) + ) { + throw new Error(`Invalid runtime getter identifier: ${identifier}`); + } + } + + private assertBindingGetterAvailable(module: PythonModule, identifier: string): void { + const occupied = new Set([ + 'getRuntimeBridge', + 'createReturnValidator', + 'selectOverloadReturnValidator', + 'ReturnSchema', + '__tywrapReturnDefinitions', + '__tywrapFloat16Value', + '__tywrapFloat16Tensor', + '__tywrapCreateApi', + '__args', + '__kwargs', + '__candidate', + '__varargs', + '__positionalOnly', + '__requiredKwOnly', + '__missing', + '__selectedReturnValidator', + 'kwargs', + 'key', + ]); + const includeCallable = (func: PythonFunction, owner = ''): void => { + occupied.add(this.escapeIdentifier(func.name)); + occupied.add( + `__validate${owner}${this.escapeIdentifier(func.name, { preserveCase: true })}Result` + ); + for (const parameter of [ + ...func.parameters, + ...(func.overloads ?? []).flatMap(overload => overload.parameters), + ]) { + occupied.add(this.escapeIdentifier(parameter.name)); + } + }; + module.functions.forEach(func => includeCallable(func)); + for (const cls of module.classes) { + occupied.add(this.escapeIdentifier(cls.name)); + const owner = this.escapeIdentifier(cls.name, { preserveCase: true }); + cls.methods.forEach(method => includeCallable(method, owner)); + } + (module.typeAliases ?? []).forEach(alias => occupied.add(this.escapeIdentifier(alias.name))); + if (occupied.has(identifier)) { + throw new Error(`Runtime getter identifier ${identifier} conflicts with a generated binding`); + } + } + /** * Convert Python snake_case to TypeScript camelCase and escape reserved words */ @@ -349,6 +521,33 @@ export class CodeGenerator { ); } + private resolvedReturnType( + contract: ValueContractV3 | undefined, + logicalType: PythonType, + ctx: GenericRenderContext + ): string { + if (contract && containsExactInteger(contract)) { + return valueContractToTsType(contract); + } + if (contract?.kind === 'ndarray-float16') { + return '__tywrapFloat16Value'; + } + if (contract?.kind === 'torch-float16') { + return '__tywrapFloat16Tensor'; + } + return this.typeToTsFromPython(logicalType, ctx, 'return'); + } + + private resolvedParameterType( + contract: ValueContractV3 | undefined, + logicalType: PythonType, + ctx: GenericRenderContext + ): string { + return contract && containsExactInteger(contract) + ? valueContractToTsType(contract) + : this.typeToTsFromPython(logicalType, ctx, 'value'); + } + private isLocalTypeIdentity( type: { name: string; module?: string }, ctx: GenericRenderContext @@ -492,7 +691,10 @@ export class CodeGenerator { values: schema(current.typeArgs[1] ?? { kind: 'custom', name: 'Any' }), }; } - return definitions.has(leaf) ? { kind: 'ref', name: leaf } : { kind: 'any' }; + return definitions.has(leaf) && + (current.module === undefined || current.module === definitions.moduleName) + ? { kind: 'ref', name: leaf } + : { kind: 'any' }; } case 'custom': { const leaf = current.name.split('.').at(-1) ?? current.name; @@ -527,7 +729,10 @@ export class CodeGenerator { ) { return { kind: 'marker', marker: 'sklearn.estimator' }; } - return definitions.has(leaf) ? { kind: 'ref', name: leaf } : { kind: 'any' }; + return definitions.has(leaf) && + (current.module === undefined || current.module === definitions.moduleName) + ? { kind: 'ref', name: leaf } + : { kind: 'any' }; } case 'typevar': case 'paramspec': @@ -542,12 +747,71 @@ export class CodeGenerator { return schema(type); } + private resolvedReturnSchema( + func: PythonFunction, + definitions: ReturnDefinitionNames + ): ReturnSchema { + const value = func.callableContract?.returnValue; + return value + ? valueContractToReturnSchema(value) + : (this.returnSchema( + func.callableContract?.returnValidationType ?? func.returnType, + definitions + ) as ReturnSchema); + } + + private overloadReturnSchemas( + func: PythonFunction, + definitions: ReturnDefinitionNames + ): OverloadReturnSchema[] { + return (func.overloads ?? []).map((overload, overloadIndex) => { + const contract = func.callableContract?.overloads[overloadIndex]; + return { + parameters: overload.parameters + .map((parameter, parameterIndex) => ({ parameter, parameterIndex })) + .filter(({ parameter }) => parameter.name !== 'self' && parameter.name !== 'cls') + .map(({ parameter, parameterIndex }) => ({ + name: parameter.name, + kind: parameter.varArgs + ? ('var-positional' as const) + : parameter.kwArgs + ? ('var-keyword' as const) + : parameter.keywordOnly + ? ('keyword-only' as const) + : parameter.positionalOnly + ? ('positional-only' as const) + : ('positional-or-keyword' as const), + optional: parameter.optional, + value: contract?.parameterValues[parameterIndex] + ? valueContractToReturnSchema(contract.parameterValues[parameterIndex]) + : (this.returnSchema(parameter.type, definitions) as ReturnSchema), + })), + result: contract?.returnValue + ? valueContractToReturnSchema(contract.returnValue) + : (this.returnSchema( + contract?.returnValidationType ?? overload.returnType, + definitions + ) as ReturnSchema), + selectable: + contract !== undefined && + contract.returnValue !== undefined && + overload.parameters.every( + (parameter, index) => + parameter.name === 'self' || + parameter.name === 'cls' || + contract.parameterValues[index] !== undefined + ), + }; + }); + } + private returnDefinitions(module: PythonModule): ReturnDefinitionNames { - return new Set( + const names = new Set( module.classes .filter(cls => cls.kind === 'typed_dict' || cls.decorators.includes('__typed_dict__')) .map(cls => cls.name) ); + return Object.assign(names, { moduleName: module.name }); } private emitReturnDefinitions(module: PythonModule): string { @@ -574,16 +838,20 @@ export class CodeGenerator { moduleName?: string, annotatedJSDoc = false, localDeclaredNames: Set = new Set(), - returnDefinitions: ReturnDefinitionNames = new Set() + returnDefinitions: ReturnDefinitionNames = new Set(), + runtimeGetterIdentifier = 'getRuntimeBridge' ): GeneratedCode { + this.assertRuntimeGetterIdentifier(runtimeGetterIdentifier); const jsdoc = this.generateJsDoc( func.docstring, annotatedJSDoc ? func.parameters.map(p => String(p.type)) : undefined ); const filteredParams = func.parameters.filter(p => p.name !== 'self' && p.name !== 'cls'); + const hasDeclaredOverloads = (func.overloads?.length ?? 0) > 0; const keywordOnlyParams = filteredParams.filter(p => p.keywordOnly); const positionalOnlyNames = filteredParams.filter(p => p.positionalOnly).map(p => p.name); const hasVarKwArgs = filteredParams.some(p => p.kwArgs); + const varKwArgsParam = filteredParams.find(p => p.kwArgs); const needsKwargsParam = keywordOnlyParams.length > 0 || hasVarKwArgs; const varArgsParam = filteredParams.find(p => p.varArgs); @@ -592,27 +860,70 @@ export class CodeGenerator { const positionalParams = filteredParams.filter(p => !p.keywordOnly && !p.varArgs && !p.kwArgs); const genericContext = this.buildGenericRenderContext( this.getTypeParameters(func.typeParameters), - [func.returnType, ...filteredParams.map(param => param.type)], + [ + func.returnType, + ...filteredParams.map(param => param.type), + ...(func.overloads ?? []).flatMap(overload => [ + overload.returnType, + ...overload.parameters.map(parameter => parameter.type), + ]), + ], moduleName, localDeclaredNames ); const typeParamDecl = genericContext.declaration; - const tsTypeForValue = (p: (typeof filteredParams)[number]): string => - this.typeToTsFromPython(p.type, genericContext, 'value'); + const parameterContracts = new WeakMap(); + func.parameters.forEach((parameter, index) => { + const value = func.callableContract?.parameterValues[index]; + if (value) { + parameterContracts.set(parameter, value); + } + }); + func.overloads?.forEach((overload, overloadIndex) => { + overload.parameters.forEach((parameter, parameterIndex) => { + const value = + func.callableContract?.overloads[overloadIndex]?.parameterValues[parameterIndex]; + if (value) { + parameterContracts.set(parameter, value); + } + }); + }); + const tsTypeForValue = (p: Parameter): string => { + const value = parameterContracts.get(p); + return this.resolvedParameterType(value, p.type, genericContext); + }; + const hasExactParameter = (parameter: Parameter): boolean => { + const value = parameterContracts.get(parameter); + return value !== undefined && containsExactInteger(value); + }; + const varArgsType = (parameter: Parameter): string => { + if (!hasExactParameter(parameter)) { + return 'unknown[]'; + } + const item = tsTypeForValue(parameter); + return `${parameterContracts.get(parameter)?.kind === 'union' ? `(${item})` : item}[]`; + }; + const varKwargsType = (parameter: Parameter): string => + hasExactParameter(parameter) ? tsTypeForValue(parameter) : 'unknown'; const kwargsType = (() => { if (!needsKwargsParam) { return ''; } - if (keywordOnlyParams.length === 0 && hasVarKwArgs) { + if (hasDeclaredOverloads) { return 'Record'; } + if (keywordOnlyParams.length === 0 && hasVarKwArgs) { + return `Record`; + } const props = keywordOnlyParams .map(p => `${JSON.stringify(p.name)}${p.optional ? '?' : ''}: ${tsTypeForValue(p)};`) .join(' '); const obj = `{ ${props} }`; - return hasVarKwArgs ? `(${obj} & Record)` : obj; + return hasVarKwArgs + ? `(${obj} & Record)` + : obj; })(); const renderPositionalParam = ( @@ -621,7 +932,7 @@ export class CodeGenerator { ): string => { const pname = this.escapeIdentifier(p.name); const opt = !forceRequired && p.optional ? '?' : ''; - return `${pname}${opt}: ${tsTypeForValue(p)}`; + return `${pname}${opt}: ${hasDeclaredOverloads ? 'unknown' : tsTypeForValue(p)}`; }; const renderVarArgsParam = (forceRequired = false): string | null => { @@ -629,11 +940,12 @@ export class CodeGenerator { return null; } const pname = this.escapeIdentifier(varArgsParam.name); + const values = hasDeclaredOverloads ? 'unknown[]' : varArgsType(varArgsParam); if (!needsVarArgsArray) { - return `...${pname}: unknown[]`; + return `...${pname}: ${values}`; } const opt = forceRequired ? '' : '?'; - return `${pname}${opt}: unknown[]`; + return `${pname}${opt}: ${values}`; }; const renderKwargsParam = (forceRequired = false): string | null => { @@ -659,13 +971,123 @@ export class CodeGenerator { const paramDecl = implParams.join(', '); const hasKwArgs = needsKwargsParam; - const returnType = this.typeToTsFromPython(func.returnType, genericContext, 'return'); + const returnType = this.resolvedReturnType( + func.callableContract?.returnValue, + func.returnType, + genericContext + ); + const implementationReturnType = hasDeclaredOverloads ? 'unknown' : returnType; const fname = this.escapeIdentifier(func.name); const moduleId = moduleName ?? '__main__'; const validatorName = `__validate${this.escapeIdentifier(func.name, { preserveCase: true })}Result`; - const returnValidator = `const ${validatorName} = createReturnValidator(${JSON.stringify(this.returnSchema(func.returnType, returnDefinitions))}, ${JSON.stringify(`${moduleId}.${func.name}`)}, __tywrapReturnDefinitions);\n\n`; + const returnValidator = `const ${validatorName} = createReturnValidator(${JSON.stringify(this.resolvedReturnSchema(func, returnDefinitions))}, ${JSON.stringify(`${moduleId}.${func.name}`)}, __tywrapReturnDefinitions);\n\n`; + + const renderDeclaredOverload = ( + overload: NonNullable[number], + overloadIndex: number + ): string[] => { + const overloadParams = overload.parameters.filter( + parameter => parameter.name !== 'self' && parameter.name !== 'cls' + ); + const overloadPositional = overloadParams.filter( + parameter => !parameter.keywordOnly && !parameter.varArgs && !parameter.kwArgs + ); + const overloadKeywordOnly = overloadParams.filter(parameter => parameter.keywordOnly); + const overloadVarArgs = overloadParams.find(parameter => parameter.varArgs); + const overloadHasVarKwArgs = overloadParams.some(parameter => parameter.kwArgs); + const overloadVarKwArgs = overloadParams.find(parameter => parameter.kwArgs); + const overloadNeedsKwargs = overloadKeywordOnly.length > 0 || overloadHasVarKwArgs; + const overloadNeedsVarArgsArray = Boolean(overloadVarArgs) && overloadNeedsKwargs; + const overloadKwargsType = (() => { + if (!overloadNeedsKwargs) { + return ''; + } + if (overloadKeywordOnly.length === 0 && overloadHasVarKwArgs) { + return `Record`; + } + const properties = overloadKeywordOnly + .map( + parameter => + `${JSON.stringify(parameter.name)}${parameter.optional ? '?' : ''}: ${tsTypeForValue(parameter)};` + ) + .join(' '); + const object = `{ ${properties} }`; + return overloadHasVarKwArgs + ? `(${object} & Record)` + : object; + })(); + const renderPositional = (parameter: Parameter, forceRequired = false): string => + `${this.escapeIdentifier(parameter.name)}${!forceRequired && parameter.optional ? '?' : ''}: ${tsTypeForValue(parameter)}`; + const renderVarArgs = (forceRequired = false): string | null => { + if (!overloadVarArgs) { + return null; + } + if (!overloadNeedsVarArgsArray) { + return `...${this.escapeIdentifier(overloadVarArgs.name)}: ${varArgsType(overloadVarArgs)}`; + } + return `${this.escapeIdentifier(overloadVarArgs.name)}${forceRequired ? '' : '?'}: ${varArgsType(overloadVarArgs)}`; + }; + const renderKwargs = (forceRequired = false): string | null => + overloadNeedsKwargs ? `kwargs${forceRequired ? '' : '?'}: ${overloadKwargsType}` : null; + const overloadReturnType = this.resolvedReturnType( + func.callableContract?.overloads[overloadIndex]?.returnValue, + overload.returnType, + genericContext + ); + const signatures: string[] = []; + const addSignature = (parameters: string[]): void => { + signatures.push( + `export function ${fname}${typeParamDecl}(${parameters.join(', ')}): Promise<${overloadReturnType}>;` + ); + }; + const firstOptional = overloadPositional.findIndex(parameter => parameter.optional); + const requiredPositionalCount = + firstOptional >= 0 ? firstOptional : overloadPositional.length; + const requiredKwOnly = overloadKeywordOnly.some(parameter => !parameter.optional); + + if (requiredKwOnly) { + for (let count = requiredPositionalCount; count <= overloadPositional.length; count += 1) { + const head = overloadPositional + .slice(0, count) + .map(parameter => renderPositional(parameter, true)); + const rest: string[] = []; + if (overloadVarArgs) { + if (overloadNeedsVarArgsArray) { + rest.push( + `${this.escapeIdentifier(overloadVarArgs.name)}: ${varArgsType(overloadVarArgs)} | undefined` + ); + } else { + rest.push( + `...${this.escapeIdentifier(overloadVarArgs.name)}: ${varArgsType(overloadVarArgs)}` + ); + } + } + const kwargs = renderKwargs(true); + if (kwargs) { + rest.push(kwargs); + } + addSignature([...head, ...rest]); + if (overloadVarArgs && overloadNeedsVarArgsArray && kwargs) { + addSignature([...head, kwargs]); + } + } + return signatures; + } - // Overloads: generate trailing optional parameter drop variants (exclude *args/**kwargs). + const parameters = overloadPositional.map(parameter => renderPositional(parameter)); + const varArgs = renderVarArgs(); + if (varArgs) { + parameters.push(varArgs); + } + const kwargs = renderKwargs(); + if (kwargs) { + parameters.push(kwargs); + } + addSignature(parameters); + return signatures; + }; + + // Optional parameter overloads make Python's trailing defaults available to TypeScript callers. // Why: Python APIs frequently have many optional tail params. TypeScript callers expect // `fn(a)`, `fn(a, b)`, ... all to typecheck. We emit a family of overloads that progressively // "drop" optional tail args, but also include the full positional signature (<= length) so a @@ -673,8 +1095,8 @@ export class CodeGenerator { const firstOptionalIndex = positionalParams.findIndex(p => p.optional); const requiredKwOnlyNames = keywordOnlyParams.filter(p => !p.optional).map(p => p.name); const keywordOnlyNames = keywordOnlyParams.map(p => p.name); - const overloads: string[] = []; - if (requiredKwOnlyNames.length > 0) { + const overloads: string[] = (func.overloads ?? []).flatMap(renderDeclaredOverload); + if ((func.overloads?.length ?? 0) === 0 && requiredKwOnlyNames.length > 0) { // Required keyword-only params must be represented with a required `kwargs` parameter. // Avoid "required after optional" by emitting overloads where all preceding parameters are required. const requiredPosCount = @@ -687,12 +1109,13 @@ export class CodeGenerator { return null; } const pname = this.escapeIdentifier(varArgsParam.name); + const values = varArgsType(varArgsParam); if (!needsVarArgsArray) { - return `...${pname}: unknown[]`; + return `...${pname}: ${values}`; } // In overloads where `kwargs` is required, keep the `args` surrogate parameter required, // but allow `undefined` as a placeholder so callers can omit varargs while still passing kwargs. - return `${pname}: unknown[] | undefined`; + return `${pname}: ${values} | undefined`; })(); if (v) { rest.push(v); @@ -711,7 +1134,12 @@ export class CodeGenerator { ); } } - } else if (firstOptionalIndex >= 0 && !varArgsParam && !needsKwargsParam) { + } else if ( + (func.overloads?.length ?? 0) === 0 && + firstOptionalIndex >= 0 && + !varArgsParam && + !needsKwargsParam + ) { for (let i = firstOptionalIndex; i <= positionalParams.length; i++) { const head = positionalParams.slice(0, i).map(p => renderPositionalParam(p)); const rest: string[] = []; @@ -751,9 +1179,14 @@ export class CodeGenerator { const guards = guardLines.length > 0 ? `${guardLines.join('\n')}\n` : ''; const callPreludeLines = emitCallPrelude(callDescriptor, this.callEmitHelpers()); const callPrelude = callPreludeLines.length > 0 ? `${callPreludeLines.join('\n')}\n` : ''; - - const ts = `${jsdoc}${returnValidator}${overloadDecl}export async function ${fname}${typeParamDecl}(${paramDecl}): Promise<${returnType}> { -${callPrelude}${guards} return getRuntimeBridge().call<${returnType}>('${moduleId}', '${func.name}', __args, ${hasKwArgs ? '__kwargs' : 'undefined'}, ${validatorName}); + const overloadValidator = + (func.overloads?.length ?? 0) > 0 + ? ` const __selectedReturnValidator = selectOverloadReturnValidator(${JSON.stringify(this.overloadReturnSchemas(func, returnDefinitions))}, __args, ${hasKwArgs ? '__kwargs' : 'undefined'}, ${validatorName}, ${JSON.stringify(`${moduleId}.${func.name}`)}, __tywrapReturnDefinitions);\n` + : ''; + const selectedValidatorName = overloadValidator ? '__selectedReturnValidator' : validatorName; + + const ts = `${jsdoc}${returnValidator}${overloadDecl}export async function ${fname}${hasDeclaredOverloads ? '' : typeParamDecl}(${paramDecl}): Promise<${implementationReturnType}> { +${callPrelude}${guards}${overloadValidator} return ${runtimeGetterIdentifier}().call<${implementationReturnType}>('${moduleId}', '${func.name}', __args, ${hasKwArgs ? '__kwargs' : 'undefined'}, ${selectedValidatorName}); } `; @@ -770,8 +1203,10 @@ ${callPrelude}${guards} return getRuntimeBridge().call<${returnType}>('${module moduleName?: string, _annotatedJSDoc = false, localDeclaredNames: Set = new Set(), - returnDefinitions: ReturnDefinitionNames = new Set() + returnDefinitions: ReturnDefinitionNames = new Set(), + runtimeGetterIdentifier = 'getRuntimeBridge' ): GeneratedCode { + this.assertRuntimeGetterIdentifier(runtimeGetterIdentifier); const moduleDeclaredNames = new Set(localDeclaredNames); moduleDeclaredNames.add(cls.name); const jsdoc = this.generateJsDoc(cls.docstring); @@ -886,6 +1321,7 @@ ${callPrelude}${guards} return getRuntimeBridge().call<${returnType}>('${module // the ordinary module call path and never retain process-local state. const staticPrefix = 'static '; const fparams = method.parameters.filter(p => p.name !== 'self' && p.name !== 'cls'); + const hasDeclaredOverloads = (method.overloads?.length ?? 0) > 0; const methodOwnGenericContext = this.buildGenericRenderContext( this.getTypeParameters(method.typeParameters), [method.returnType, ...fparams.map(param => param.type)], @@ -897,11 +1333,31 @@ ${callPrelude}${guards} return getRuntimeBridge().call<${returnType}>('${module methodOwnGenericContext ); const methodTypeParamDecl = methodOwnGenericContext.declaration; - const methodTsValueType = (p: (typeof fparams)[number]): string => - this.typeToTsFromPython(p.type, methodGenericContext, 'value'); + const methodParameterContracts = new WeakMap(); + method.parameters.forEach((parameter, index) => { + const value = method.callableContract?.parameterValues[index]; + if (value) { + methodParameterContracts.set(parameter, value); + } + }); + const methodTsValueType = (p: Parameter): string => + this.resolvedParameterType(methodParameterContracts.get(p), p.type, methodGenericContext); + const methodVarArgsType = (p: Parameter): string => { + const value = methodParameterContracts.get(p); + if (!value || !containsExactInteger(value)) { + return 'unknown[]'; + } + const item = methodTsValueType(p); + return `${value.kind === 'union' ? `(${item})` : item}[]`; + }; + const methodVarKwargsType = (p: Parameter): string => { + const value = methodParameterContracts.get(p); + return value && containsExactInteger(value) ? methodTsValueType(p) : 'unknown'; + }; const keywordOnlyParams = fparams.filter(p => p.keywordOnly); const positionalOnlyNames = fparams.filter(p => p.positionalOnly).map(p => p.name); const hasVarKwArgs = fparams.some(p => p.kwArgs); + const varKwArgsParam = fparams.find(p => p.kwArgs); const needsKwargsParam = keywordOnlyParams.length > 0 || hasVarKwArgs; const varArgsParam = fparams.find(p => p.varArgs); const needsVarArgsArray = Boolean(varArgsParam) && needsKwargsParam; @@ -917,21 +1373,26 @@ ${callPrelude}${guards} return getRuntimeBridge().call<${returnType}>('${module ): string => { const pname = this.escapeIdentifier(p.name); const opt = !forceRequired && p.optional ? '?' : ''; - return `${pname}${opt}: ${methodTsValueType(p)}`; + return `${pname}${opt}: ${hasDeclaredOverloads ? 'unknown' : methodTsValueType(p)}`; }; const kwargsType = (() => { if (!needsKwargsParam) { return ''; } - if (keywordOnlyParams.length === 0 && hasVarKwArgs) { + if (hasDeclaredOverloads) { return 'Record'; } + if (keywordOnlyParams.length === 0 && hasVarKwArgs) { + return `Record`; + } const props = keywordOnlyParams .map(p => `${JSON.stringify(p.name)}${p.optional ? '?' : ''}: ${methodTsValueType(p)};`) .join(' '); const obj = `{ ${props} }`; - return hasVarKwArgs ? `(${obj} & Record)` : obj; + return hasVarKwArgs + ? `(${obj} & Record)` + : obj; })(); const paramsDeclParts: string[] = []; @@ -941,7 +1402,9 @@ ${callPrelude}${guards} return getRuntimeBridge().call<${returnType}>('${module if (varArgsParam) { const vname = this.escapeIdentifier(varArgsParam.name); paramsDeclParts.push( - needsVarArgsArray ? `${vname}?: unknown[]` : `...${vname}: unknown[]` + needsVarArgsArray + ? `${vname}?: ${hasDeclaredOverloads ? 'unknown[]' : methodVarArgsType(varArgsParam)}` + : `...${vname}: ${hasDeclaredOverloads ? 'unknown[]' : methodVarArgsType(varArgsParam)}` ); } if (needsKwargsParam) { @@ -950,17 +1413,59 @@ ${callPrelude}${guards} return getRuntimeBridge().call<${returnType}>('${module const paramsDecl = paramsDeclParts.join(', '); const requiredKwOnlyNames = keywordOnlyParams.filter(p => !p.optional).map(p => p.name); - const returnType = this.typeToTsFromPython( + const returnType = this.resolvedReturnType( + method.callableContract?.returnValue, method.returnType, - methodGenericContext, - 'return' + methodGenericContext ); + const implementationReturnType = hasDeclaredOverloads ? 'unknown' : returnType; const mname = this.escapeIdentifier(method.name); const validatorName = `__validate${this.escapeIdentifier(cls.name, { preserveCase: true })}${this.escapeIdentifier(method.name, { preserveCase: true })}Result`; - const returnValidator = `const ${validatorName} = createReturnValidator(${JSON.stringify(this.returnSchema(method.returnType, returnDefinitions))}, ${JSON.stringify(`${moduleId}.${cls.name}.${method.name}`)}, __tywrapReturnDefinitions);\n\n`; - - const overloads: string[] = []; - if (needsKwargsParam && requiredKwOnlyNames.length > 0) { + const returnValidator = `const ${validatorName} = createReturnValidator(${JSON.stringify(this.resolvedReturnSchema(method, returnDefinitions))}, ${JSON.stringify(`${moduleId}.${cls.name}.${method.name}`)}, __tywrapReturnDefinitions);\n\n`; + + const declaredOverloads = + (method.overloads?.length ?? 0) > 0 + ? (this.generateFunctionWrapper( + { + ...method, + parameters: fparams, + callableContract: method.callableContract + ? { + ...method.callableContract, + parameterValues: method.callableContract.parameterValues.filter( + (_, index) => + method.parameters[index]?.name !== 'self' && + method.parameters[index]?.name !== 'cls' + ), + overloads: method.callableContract.overloads.map((contract, index) => ({ + ...contract, + parameterValues: contract.parameterValues.filter( + (_, parameterIndex) => + method.overloads?.[index]?.parameters[parameterIndex]?.name !== + 'self' && + method.overloads?.[index]?.parameters[parameterIndex]?.name !== 'cls' + ), + })), + } + : undefined, + overloads: method.overloads?.map(overload => ({ + ...overload, + parameters: overload.parameters.filter( + p => p.name !== 'self' && p.name !== 'cls' + ), + })), + }, + moduleName, + false, + moduleDeclaredNames, + returnDefinitions, + runtimeGetterIdentifier + ) + .declaration.match(/^export function .*;$/gm) + ?.map(line => ` static ${line.slice('export function '.length)}`) ?? []) + : []; + const overloads: string[] = [...declaredOverloads]; + if (declaredOverloads.length === 0 && needsKwargsParam && requiredKwOnlyNames.length > 0) { const firstOptionalIndex = positionalParams.findIndex(p => p.optional); const requiredPosCount = firstOptionalIndex >= 0 ? firstOptionalIndex : positionalParams.length; @@ -970,7 +1475,9 @@ ${callPrelude}${guards} return getRuntimeBridge().call<${returnType}>('${module if (varArgsParam) { const vname = this.escapeIdentifier(varArgsParam.name); rest.push( - needsVarArgsArray ? `${vname}: unknown[] | undefined` : `...${vname}: unknown[]` + needsVarArgsArray + ? `${vname}: ${methodVarArgsType(varArgsParam)} | undefined` + : `...${vname}: ${methodVarArgsType(varArgsParam)}` ); } rest.push(`kwargs: ${kwargsType}`); @@ -1004,10 +1511,17 @@ ${callPrelude}${guards} return getRuntimeBridge().call<${returnType}>('${module const guardLines = emitArgGuards(callDescriptor); const guards = guardLines.length > 0 ? `${guardLines.join('\n')}\n` : ''; - - const callExpr = `getRuntimeBridge().call<${returnType}>('${moduleId}', '${cls.name}.${method.name}', __args, ${needsKwargsParam ? '__kwargs' : 'undefined'}, ${validatorName})`; - methodBodies.push(`${overloadDecl} ${staticPrefix}async ${mname}${methodTypeParamDecl}(${paramsDecl}): Promise<${returnType}> { - ${returnValidator}${callPrelude}${guards} return ${callExpr}; + const overloadValidator = + declaredOverloads.length > 0 + ? ` const __selectedReturnValidator = selectOverloadReturnValidator(${JSON.stringify(this.overloadReturnSchemas(method, returnDefinitions))}, __args, ${needsKwargsParam ? '__kwargs' : 'undefined'}, ${validatorName}, ${JSON.stringify(`${moduleId}.${cls.name}.${method.name}`)}, __tywrapReturnDefinitions);\n` + : ''; + const selectedValidatorName = overloadValidator + ? '__selectedReturnValidator' + : validatorName; + + const callExpr = `${runtimeGetterIdentifier}().call<${implementationReturnType}>('${moduleId}', '${cls.name}.${method.name}', __args, ${needsKwargsParam ? '__kwargs' : 'undefined'}, ${selectedValidatorName})`; + methodBodies.push(`${overloadDecl} ${staticPrefix}async ${mname}${hasDeclaredOverloads ? '' : methodTypeParamDecl}(${paramsDecl}): Promise<${implementationReturnType}> { + ${returnValidator}${callPrelude}${guards}${overloadValidator} return ${callExpr}; }`); methodDeclarations.push( `${overloadDecl}${overloads.length > 0 ? '' : ` ${staticPrefix}${mname}${methodTypeParamDecl}(${paramsDecl}): Promise<${returnType}>;\n`}` @@ -1081,6 +1595,30 @@ ${migrationNote}${declarationMethodsSection} } generateModuleDefinition(module: PythonModule, annotatedJSDoc = false): GeneratedCode { + return this.generateModuleWithGetter(module, annotatedJSDoc, 'getRuntimeBridge', true); + } + + /** Build an intermediate template. The caller must bind its provider before emission. */ + generateModuleBindingTemplate( + module: PythonModule, + annotatedJSDoc = false, + runtimeGetterIdentifier = '__tywrapRuntimeProvider' + ): GeneratedCode { + if (runtimeGetterIdentifier === 'getRuntimeBridge') { + throw new Error('Binding templates require a distinct runtime getter'); + } + this.assertRuntimeGetterIdentifier(runtimeGetterIdentifier); + this.assertBindingGetterAvailable(module, runtimeGetterIdentifier); + return this.generateModuleWithGetter(module, annotatedJSDoc, runtimeGetterIdentifier, false); + } + + private generateModuleWithGetter( + module: PythonModule, + annotatedJSDoc: boolean, + runtimeGetterIdentifier: string, + importRuntimeGetter: boolean + ): GeneratedCode { + this.assertRuntimeGetterIdentifier(runtimeGetterIdentifier); const localDeclaredNames = new Set([ ...module.classes.map(cls => cls.name), ...(module.typeAliases ?? []).map(alias => alias.name), @@ -1093,7 +1631,8 @@ ${migrationNote}${declarationMethodsSection} module.name, annotatedJSDoc, localDeclaredNames, - this.returnDefinitions(module) + this.returnDefinitions(module), + runtimeGetterIdentifier ) ); const classResults = [...module.classes] @@ -1104,7 +1643,8 @@ ${migrationNote}${declarationMethodsSection} module.name, annotatedJSDoc, localDeclaredNames, - this.returnDefinitions(module) + this.returnDefinitions(module), + runtimeGetterIdentifier ) ); const typeAliasResults = [...(module.typeAliases ?? [])] @@ -1122,12 +1662,48 @@ ${migrationNote}${declarationMethodsSection} return kind === 'class' && !c.decorators.includes('__typed_dict__'); }); const needsRuntime = module.functions.length > 0 || hasRuntimeClasses; + const hasOverloads = + module.functions.some(func => (func.overloads?.length ?? 0) > 0) || + module.classes.some(cls => cls.methods.some(method => (method.overloads?.length ?? 0) > 0)); + const emittedCallables = [ + ...module.functions, + ...module.classes.flatMap(cls => + cls.methods.filter( + method => + method.name !== '__init__' && + (method.methodKind === 'class' || method.methodKind === 'static') + ) + ), + ]; + const resolvedValues = emittedCallables.flatMap(func => [ + ...(func.callableContract?.parameterValues ?? []), + func.callableContract?.returnValue, + ...(func.callableContract?.overloads.flatMap(overload => [ + ...overload.parameterValues, + overload.returnValue, + ]) ?? []), + ]); + const needsTorchFloat16 = resolvedValues.some( + value => value !== undefined && containsScientificValue(value, 'torch-float16') + ); + const needsFloat16 = + needsTorchFloat16 || + resolvedValues.some( + value => value !== undefined && containsScientificValue(value, 'ndarray-float16') + ); + const scientificTypes = needsFloat16 + ? `type __tywrapFloat16Value = number | __tywrapFloat16Value[];\n${ + needsTorchFloat16 + ? `type __tywrapFloat16Tensor = { data: __tywrapFloat16Value; shape: number[]; dtype: 'torch.float16'; device?: string; sourceDtype?: string; sourceDevice?: string };\n` + : '' + }\n` + : ''; const bridgeDecl = needsRuntime - ? `import { createReturnValidator, getRuntimeBridge, type ReturnSchema } from 'tywrap/runtime';\n\n${this.emitReturnDefinitions(module)}` + ? `import { createReturnValidator, ${hasOverloads ? 'selectOverloadReturnValidator, ' : ''}${importRuntimeGetter ? 'getRuntimeBridge, ' : ''}type ReturnSchema } from 'tywrap/runtime';\n\n${this.emitReturnDefinitions(module)}` : ''; - const ts = `${`${header}${bridgeDecl}${functionCodes}\n${classCodes}\n${typeAliasCodes}`.trimEnd()}\n`; - const declaration = `${`${declarationHeader}${functionResults + const ts = `${`${header}${bridgeDecl}${scientificTypes}${functionCodes}\n${classCodes}\n${typeAliasCodes}`.trimEnd()}\n`; + const declaration = `${`${declarationHeader}${scientificTypes}${functionResults .map(result => result.declaration) .join('\n')}\n${classResults .map(result => result.declaration) @@ -1158,7 +1734,7 @@ ${migrationNote}${declarationMethodsSection} declaration, sourceMap: undefined, metadata: { - generatedAt: new Date(), + generatedAt: new Date(0), sourceFiles: [], runtime: 'auto', optimizations: [], diff --git a/src/core/ir-contract.ts b/src/core/ir-contract.ts new file mode 100644 index 00000000..9ff2ded2 --- /dev/null +++ b/src/core/ir-contract.ts @@ -0,0 +1,553 @@ +/** + * Validate the JSON contract emitted by tywrap_ir 0.4 before compilation. + * + * This module does not read files, start Python, or write generated output. + * It only accepts unknown JSON-compatible input and returns located diagnostics. + */ + +import type { IrContract } from '../types/index.js'; + +export const TYWRAP_IR_VERSION = '0.4.0' as const; + +const PARAMETER_KINDS = new Set([ + 'POSITIONAL_ONLY', + 'POSITIONAL_OR_KEYWORD', + 'VAR_POSITIONAL', + 'KEYWORD_ONLY', + 'VAR_KEYWORD', +]); +const FIELD_KINDS = new Set([...PARAMETER_KINDS, 'FIELD']); + +const METHOD_KINDS = new Set(['instance', 'class', 'static']); +const TYPE_PARAMETER_KINDS = new Set(['typevar', 'paramspec', 'typevartuple']); +const VARIANCES = new Set(['covariant', 'contravariant', 'invariant']); + +export interface IrParameter { + name: string; + kind: string; + annotation: string | null; + default: boolean; +} + +export interface IrTypeParameter { + name: string; + kind: 'typevar' | 'paramspec' | 'typevartuple'; + bound: string | null; + constraints: string[] | null; + variance: 'covariant' | 'contravariant' | 'invariant' | null; +} + +export interface IrOverload { + parameters: IrParameter[]; + returns: string | null; +} + +export interface IrFunction { + name: string; + qualname: string; + docstring: string | null; + parameters: IrParameter[]; + returns: string | null; + is_async: boolean; + is_generator: boolean; + type_params: IrTypeParameter[]; + method_kind: 'instance' | 'class' | 'static'; + overloads: IrOverload[]; +} + +export interface IrAccessor { + name: string; + returns: string | null; + docstring: string | null; + read_only: boolean | null; + is_cached: boolean; +} + +export interface IrClass { + name: string; + qualname: string; + docstring: string | null; + bases: string[]; + methods: IrFunction[]; + typed_dict: boolean; + total: boolean | null; + fields: IrParameter[]; + is_protocol: boolean; + is_namedtuple: boolean; + is_dataclass: boolean; + is_pydantic: boolean; + type_params: IrTypeParameter[]; + accessors: IrAccessor[]; +} + +export interface IrConstant { + name: string; + annotation: string | null; + value_repr: string | null; + is_final: boolean; +} + +export interface IrTypeAlias { + name: string; + definition: string; + is_generic: boolean; + type_params: IrTypeParameter[]; +} + +export interface ValidatedIrContract extends IrContract { + ir_version: typeof TYWRAP_IR_VERSION; + module: string; + functions: IrFunction[]; + classes: IrClass[]; + constants: IrConstant[]; + type_aliases: IrTypeAlias[]; + metadata: Record; + warnings: string[]; +} + +export interface IrDiagnostic { + code: 'ir-version-mismatch' | 'contract-invalid'; + path: string; + message: string; +} + +export interface ValidateIrContractOptions { + /** + * Generated offline contracts omit extractor metadata so their bytes stay + * stable. The reader restores an empty metadata object for that format. + */ + allowOmittedMetadata?: boolean; +} + +export type IrValidationResult = + | { ok: true; contract: ValidatedIrContract; diagnostics: readonly [] } + | { ok: false; contract: null; diagnostics: readonly IrDiagnostic[] }; + +class ValidationState { + readonly diagnostics: IrDiagnostic[] = []; + private overflowed = false; + private entriesVisited = 0; + private entryBudgetExceeded = false; + + private static readonly maxDiagnostics = 100; + private static readonly maxEntries = 100_000; + + constructor(private readonly source: string) {} + + invalid(path: string, message: string): void { + if (this.diagnostics.length >= ValidationState.maxDiagnostics) { + this.overflowed = true; + return; + } + this.diagnostics.push({ code: 'contract-invalid', path, message: `${this.source} ${message}` }); + } + + versionMismatch(path: string, found: string): void { + if (this.diagnostics.length >= ValidationState.maxDiagnostics) { + this.overflowed = true; + return; + } + this.diagnostics.push({ + code: 'ir-version-mismatch', + path, + message: `IR version mismatch: TypeScript expects ${TYWRAP_IR_VERSION}, but ${this.source} declares ${found}. Regenerate the contract with a matching tywrap_ir.`, + }); + } + + visit(path: string): boolean { + if (this.diagnostics.length >= ValidationState.maxDiagnostics) { + this.overflowed = true; + return false; + } + if (this.entryBudgetExceeded) { + return false; + } + this.entriesVisited += 1; + if (this.entriesVisited > ValidationState.maxEntries) { + this.entryBudgetExceeded = true; + this.invalid(path, `IR exceeds the ${ValidationState.maxEntries} entry validation limit.`); + return false; + } + return true; + } + + finish(): readonly IrDiagnostic[] { + if (!this.overflowed) { + return this.diagnostics; + } + return [ + ...this.diagnostics, + { + code: 'contract-invalid', + path: '$', + message: `${this.source} has more than ${ValidationState.maxDiagnostics} contract errors.`, + }, + ]; + } +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function visitArray( + values: readonly unknown[], + path: string, + state: ValidationState, + validate: (value: unknown, path: string) => void +): void { + for (let index = 0; index < values.length; index += 1) { + const entryPath = `${path}[${index}]`; + if (!state.visit(entryPath)) { + break; + } + validate(values[index], entryPath); + } +} + +function recordAt( + value: unknown, + path: string, + state: ValidationState +): Record | null { + if (!isRecord(value)) { + state.invalid(path, `${path} must be an object.`); + return null; + } + return value; +} + +function requiredValue( + object: Record, + name: string, + path: string, + state: ValidationState +): unknown { + if (!(name in object)) { + state.invalid(`${path}.${name}`, `${path} is missing required field ${name}.`); + return undefined; + } + return object[name]; +} + +function requiredString( + object: Record, + name: string, + path: string, + state: ValidationState, + allowEmpty = false +): string | null { + const value = requiredValue(object, name, path, state); + if (typeof value !== 'string') { + state.invalid(`${path}.${name}`, `${path}.${name} must be a string.`); + return null; + } + if (!allowEmpty && value.length === 0) { + state.invalid(`${path}.${name}`, `${path}.${name} must not be empty.`); + return null; + } + return value; +} + +function requiredNullableString( + object: Record, + name: string, + path: string, + state: ValidationState +): string | null { + const value = requiredValue(object, name, path, state); + if (value === null) { + return null; + } + if (typeof value !== 'string') { + state.invalid(`${path}.${name}`, `${path}.${name} must be a string or null.`); + return null; + } + return value; +} + +function requiredBoolean( + object: Record, + name: string, + path: string, + state: ValidationState +): boolean | null { + const value = requiredValue(object, name, path, state); + if (typeof value !== 'boolean') { + state.invalid(`${path}.${name}`, `${path}.${name} must be a boolean.`); + return null; + } + return value; +} + +function requiredArray( + object: Record, + name: string, + path: string, + state: ValidationState +): unknown[] | null { + if (!(name in object)) { + const noun = path === '$' ? `required array field ${name}` : `${path}.${name}`; + state.invalid(`${path}.${name}`, `${path} is missing ${noun}.`); + return null; + } + const value = object[name]; + if (!Array.isArray(value)) { + state.invalid(`${path}.${name}`, `${path}.${name} must be an array.`); + return null; + } + return value; +} + +function validateStringArray(value: unknown, path: string, state: ValidationState): void { + if (!Array.isArray(value)) { + state.invalid(path, `${path} must be an array.`); + return; + } + visitArray(value, path, state, (entry, entryPath) => { + if (typeof entry !== 'string') { + state.invalid(entryPath, `${entryPath} must be a string.`); + } + }); +} + +function validateParameter( + value: unknown, + path: string, + state: ValidationState, + allowedKinds: ReadonlySet = PARAMETER_KINDS +): void { + const parameter = recordAt(value, path, state); + if (!parameter) { + return; + } + requiredString(parameter, 'name', path, state); + const kind = requiredString(parameter, 'kind', path, state); + if (kind !== null && !allowedKinds.has(kind)) { + state.invalid(`${path}.kind`, `${path}.kind must be a supported Python parameter kind.`); + } + requiredNullableString(parameter, 'annotation', path, state); + requiredBoolean(parameter, 'default', path, state); +} + +function validateTypeParameter(value: unknown, path: string, state: ValidationState): void { + const parameter = recordAt(value, path, state); + if (!parameter) { + return; + } + requiredString(parameter, 'name', path, state); + const kind = requiredString(parameter, 'kind', path, state); + if (kind !== null && !TYPE_PARAMETER_KINDS.has(kind)) { + state.invalid(`${path}.kind`, `${path}.kind must be typevar, paramspec, or typevartuple.`); + } + requiredNullableString(parameter, 'bound', path, state); + const constraints = requiredValue(parameter, 'constraints', path, state); + if (constraints !== null) { + validateStringArray(constraints, `${path}.constraints`, state); + } + const variance = requiredValue(parameter, 'variance', path, state); + if (variance !== null && (typeof variance !== 'string' || !VARIANCES.has(variance))) { + state.invalid(`${path}.variance`, `${path}.variance must be a supported variance or null.`); + } +} + +function validateFunction(value: unknown, path: string, state: ValidationState): void { + const callable = recordAt(value, path, state); + if (!callable) { + return; + } + requiredString(callable, 'name', path, state); + requiredString(callable, 'qualname', path, state); + requiredNullableString(callable, 'docstring', path, state); + const parameters = requiredArray(callable, 'parameters', path, state); + if (parameters) { + visitArray(parameters, `${path}.parameters`, state, (parameter, entryPath) => + validateParameter(parameter, entryPath, state) + ); + } + requiredNullableString(callable, 'returns', path, state); + requiredBoolean(callable, 'is_async', path, state); + requiredBoolean(callable, 'is_generator', path, state); + const typeParameters = requiredArray(callable, 'type_params', path, state); + if (typeParameters) { + visitArray(typeParameters, `${path}.type_params`, state, (parameter, entryPath) => + validateTypeParameter(parameter, entryPath, state) + ); + } + const methodKind = requiredString(callable, 'method_kind', path, state); + if (methodKind !== null && !METHOD_KINDS.has(methodKind)) { + state.invalid(`${path}.method_kind`, `${path}.method_kind must be instance, class, or static.`); + } + const overloads = requiredArray(callable, 'overloads', path, state); + if (overloads) { + visitArray(overloads, `${path}.overloads`, state, (overload, overloadPath) => { + const signature = recordAt(overload, overloadPath, state); + if (!signature) { + return; + } + const overloadParameters = requiredArray(signature, 'parameters', overloadPath, state); + if (overloadParameters) { + visitArray( + overloadParameters, + `${overloadPath}.parameters`, + state, + (parameter, entryPath) => validateParameter(parameter, entryPath, state) + ); + } + requiredNullableString(signature, 'returns', overloadPath, state); + }); + } +} + +function validateAccessor(value: unknown, path: string, state: ValidationState): void { + const accessor = recordAt(value, path, state); + if (!accessor) { + return; + } + requiredString(accessor, 'name', path, state); + requiredNullableString(accessor, 'returns', path, state); + requiredNullableString(accessor, 'docstring', path, state); + const readOnly = requiredValue(accessor, 'read_only', path, state); + if (readOnly !== null && typeof readOnly !== 'boolean') { + state.invalid(`${path}.read_only`, `${path}.read_only must be a boolean or null.`); + } + requiredBoolean(accessor, 'is_cached', path, state); +} + +function validateClass(value: unknown, path: string, state: ValidationState): void { + const cls = recordAt(value, path, state); + if (!cls) { + return; + } + requiredString(cls, 'name', path, state); + requiredString(cls, 'qualname', path, state); + requiredNullableString(cls, 'docstring', path, state); + validateStringArray(requiredValue(cls, 'bases', path, state), `${path}.bases`, state); + const methods = requiredArray(cls, 'methods', path, state); + if (methods) { + visitArray(methods, `${path}.methods`, state, (method, entryPath) => + validateFunction(method, entryPath, state) + ); + } + requiredBoolean(cls, 'typed_dict', path, state); + const total = requiredValue(cls, 'total', path, state); + if (total !== null && typeof total !== 'boolean') { + state.invalid(`${path}.total`, `${path}.total must be a boolean or null.`); + } + const fields = requiredArray(cls, 'fields', path, state); + if (fields) { + visitArray(fields, `${path}.fields`, state, (field, entryPath) => + validateParameter(field, entryPath, state, FIELD_KINDS) + ); + } + requiredBoolean(cls, 'is_protocol', path, state); + requiredBoolean(cls, 'is_namedtuple', path, state); + requiredBoolean(cls, 'is_dataclass', path, state); + requiredBoolean(cls, 'is_pydantic', path, state); + const typeParameters = requiredArray(cls, 'type_params', path, state); + if (typeParameters) { + visitArray(typeParameters, `${path}.type_params`, state, (parameter, entryPath) => + validateTypeParameter(parameter, entryPath, state) + ); + } + const accessors = requiredArray(cls, 'accessors', path, state); + if (accessors) { + visitArray(accessors, `${path}.accessors`, state, (accessor, entryPath) => + validateAccessor(accessor, entryPath, state) + ); + } +} + +function validateConstant(value: unknown, path: string, state: ValidationState): void { + const constant = recordAt(value, path, state); + if (!constant) { + return; + } + requiredString(constant, 'name', path, state); + requiredNullableString(constant, 'annotation', path, state); + requiredNullableString(constant, 'value_repr', path, state); + requiredBoolean(constant, 'is_final', path, state); +} + +function validateTypeAlias(value: unknown, path: string, state: ValidationState): void { + const alias = recordAt(value, path, state); + if (!alias) { + return; + } + requiredString(alias, 'name', path, state); + requiredString(alias, 'definition', path, state, true); + requiredBoolean(alias, 'is_generic', path, state); + const typeParameters = requiredArray(alias, 'type_params', path, state); + if (typeParameters) { + visitArray(typeParameters, `${path}.type_params`, state, (parameter, entryPath) => + validateTypeParameter(parameter, entryPath, state) + ); + } +} + +/** + * Validate every field emitted by `tywrap_ir` 0.4. + * + * The return value is safe to compile without further structural checks. The + * caller owns all filesystem, cache, interpreter, and output operations. + */ +export function validateIrContract( + input: unknown, + source = 'IR', + options: ValidateIrContractOptions = {} +): IrValidationResult { + const state = new ValidationState(source); + const contract = recordAt(input, '$', state); + if (!contract) { + return { ok: false, contract: null, diagnostics: state.finish() }; + } + + const version = requiredString(contract, 'ir_version', '$', state); + if (version !== null && version !== TYWRAP_IR_VERSION) { + state.versionMismatch('$.ir_version', version); + } + requiredString(contract, 'module', '$', state); + const functions = requiredArray(contract, 'functions', '$', state); + if (functions) { + visitArray(functions, '$.functions', state, (functionValue, entryPath) => + validateFunction(functionValue, entryPath, state) + ); + } + const classes = requiredArray(contract, 'classes', '$', state); + if (classes) { + visitArray(classes, '$.classes', state, (classValue, entryPath) => + validateClass(classValue, entryPath, state) + ); + } + const constants = requiredArray(contract, 'constants', '$', state); + if (constants) { + visitArray(constants, '$.constants', state, (constant, entryPath) => + validateConstant(constant, entryPath, state) + ); + } + const aliases = requiredArray(contract, 'type_aliases', '$', state); + if (aliases) { + visitArray(aliases, '$.type_aliases', state, (alias, entryPath) => + validateTypeAlias(alias, entryPath, state) + ); + } + const metadata = contract.metadata; + if (metadata === undefined && !options.allowOmittedMetadata) { + state.invalid('$.metadata', '$ is missing required field metadata.'); + } else if (metadata !== undefined && !isRecord(metadata)) { + state.invalid('$.metadata', '$.metadata must be an object.'); + } + validateStringArray(requiredValue(contract, 'warnings', '$', state), '$.warnings', state); + + if (state.diagnostics.length > 0) { + return { ok: false, contract: null, diagnostics: state.finish() }; + } + return { + ok: true, + contract: { + ...contract, + metadata: isRecord(metadata) ? metadata : {}, + } as ValidatedIrContract, + diagnostics: [], + }; +} diff --git a/src/core/ir-model.ts b/src/core/ir-model.ts new file mode 100644 index 00000000..b4526b12 --- /dev/null +++ b/src/core/ir-model.ts @@ -0,0 +1,165 @@ +/** Map validated Python IR to the generator model without runtime effects. */ + +import { parseAnnotationToPythonType } from './annotation-parser.js'; +import type { + IrClass, + IrFunction, + IrParameter, + IrTypeAlias, + IrTypeParameter, + ValidatedIrContract, +} from './ir-contract.js'; +import type { + Parameter, + PythonClass, + PythonFunction, + PythonGenericParameter, + PythonModule, + PythonType, + PythonTypeAlias, +} from '../types/index.js'; + +function collectModuleTypeVarNames(ir: ValidatedIrContract): Set { + const names = new Set(); + for (const constant of ir.constants) { + const name = constant.name.trim(); + if (!name) { + continue; + } + const valueRepr = constant.value_repr?.trim() ?? ''; + if (/^~?[A-Za-z_][A-Za-z0-9_]*$/.test(valueRepr) && valueRepr.replace(/^~/, '') === name) { + names.add(name); + continue; + } + const annotation = constant.annotation?.trim() ?? ''; + if (/(^|\.)(TypeVar|ParamSpec|TypeVarTuple)(\[|\(|$)/.test(annotation)) { + names.add(name); + } + } + return names; +} + +export function transformIrToTsModel( + ir: ValidatedIrContract, + onUnknownTypeName?: (name: string) => void +): PythonModule { + const moduleTypeVarNames = collectModuleTypeVarNames(ir); + const parseType = ( + annotation: unknown, + typeParameters: readonly PythonGenericParameter[] = [] + ): PythonType => + parseAnnotationToPythonType(annotation, { + onUnknownTypeName, + knownTypeVarNames: moduleTypeVarNames, + typeParameters, + }); + const mapTypeParameters = ( + typeParameters: readonly IrTypeParameter[] + ): PythonGenericParameter[] => + typeParameters.map(param => ({ + name: param.name, + kind: param.kind, + bound: param.bound ? parseType(param.bound) : undefined, + constraints: param.constraints ? param.constraints.map(item => parseType(item)) : undefined, + variance: param.variance ?? undefined, + })); + const mapParam = ( + param: IrParameter, + typeParameters: readonly PythonGenericParameter[] = [] + ): Parameter => ({ + name: param.name, + type: parseType(param.annotation, typeParameters), + optional: param.default, + varArgs: param.kind === 'VAR_POSITIONAL', + kwArgs: param.kind === 'VAR_KEYWORD', + positionalOnly: param.kind === 'POSITIONAL_ONLY', + keywordOnly: param.kind === 'KEYWORD_ONLY', + }); + const mapMethodKind = (value: unknown): PythonFunction['methodKind'] => + value === 'class' || value === 'static' ? value : 'instance'; + const mapFunc = ( + func: IrFunction, + inheritedTypeParameters: readonly PythonGenericParameter[] = [] + ): PythonFunction => { + const localTypeParameters = mapTypeParameters(func.type_params); + const annotationTypeParameters = [...inheritedTypeParameters, ...localTypeParameters]; + return { + name: func.name, + signature: { + parameters: func.parameters.map(param => mapParam(param, annotationTypeParameters)), + returnType: parseType(func.returns, annotationTypeParameters), + isAsync: func.is_async, + isGenerator: func.is_generator, + }, + docstring: func.docstring ?? undefined, + decorators: [], + isAsync: func.is_async, + isGenerator: func.is_generator, + typeParameters: [...localTypeParameters], + returnType: parseType(func.returns, annotationTypeParameters), + parameters: func.parameters.map(param => mapParam(param, annotationTypeParameters)), + overloads: func.overloads.map(overload => ({ + parameters: overload.parameters.map(param => mapParam(param, annotationTypeParameters)), + returnType: parseType(overload.returns, annotationTypeParameters), + })), + methodKind: mapMethodKind(func.method_kind), + }; + }; + const mapClass = (cls: IrClass): PythonClass => { + const classTypeParameters = mapTypeParameters(cls.type_params); + return { + name: cls.name, + bases: cls.bases, + methods: cls.methods.map(method => mapFunc(method, classTypeParameters)), + properties: cls.fields.map(field => ({ + name: field.name, + type: parseType(field.annotation, classTypeParameters), + readonly: false, + setter: false, + getter: true, + // A constructor default does not make the returned dataclass field absent. + optional: cls.is_dataclass ? false : field.default, + })), + accessors: cls.accessors.map(accessor => ({ + name: accessor.name, + type: parseType(accessor.returns, classTypeParameters), + docstring: accessor.docstring ?? undefined, + readOnly: accessor.read_only ?? undefined, + isCached: accessor.is_cached, + })), + docstring: cls.docstring ?? undefined, + decorators: cls.typed_dict ? ['__typed_dict__'] : [], + kind: cls.typed_dict + ? 'typed_dict' + : cls.is_protocol + ? 'protocol' + : cls.is_namedtuple + ? 'namedtuple' + : cls.is_dataclass + ? 'dataclass' + : cls.is_pydantic + ? 'pydantic' + : 'class', + typeParameters: classTypeParameters, + }; + }; + const mapTypeAlias = (alias: IrTypeAlias): PythonTypeAlias => { + const typeParameters = mapTypeParameters(alias.type_params); + return { + name: alias.name, + type: parseType(alias.definition, typeParameters), + typeParameters, + }; + }; + return { + name: ir.module, + path: undefined, + version: + typeof ir.metadata.package_version === 'string' ? ir.metadata.package_version : undefined, + functions: ir.functions.map(func => mapFunc(func)), + classes: ir.classes.map(mapClass), + typeAliases: ir.type_aliases.map(mapTypeAlias), + imports: [], + exports: [], + }; +} diff --git a/src/dev.ts b/src/dev.ts index ea609308..168c2319 100644 --- a/src/dev.ts +++ b/src/dev.ts @@ -7,6 +7,7 @@ import { watch as createWatcher, type FSWatcher } from 'node:fs'; import { access, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'; +import { createHash } from 'node:crypto'; import { tmpdir } from 'node:os'; import { delimiter, dirname, join, relative, resolve, sep } from 'node:path'; @@ -56,6 +57,7 @@ interface StageResult { warnings: string[]; failures: GenerateFailure[]; watchSources: WatchSource[]; + sourceFingerprint: string; outputDir: string; } @@ -254,6 +256,55 @@ function normalizeWatchSources(sources: Iterable): WatchSource[] { .map(([path, kind]) => ({ path, kind })); } +async function fingerprintPythonSources( + sources: WatchSource[], + ignoredPaths: string[] +): Promise { + const files = new Set(); + for (const source of normalizeWatchSources(sources)) { + if (shouldIgnoreWatchPath(source.path, ignoredPaths)) { + continue; + } + if (source.kind === 'file') { + files.add(source.path); + continue; + } + + const pending = [source.path]; + while (pending.length > 0) { + const directory = pending.pop(); + if (directory === undefined) { + break; + } + if (shouldIgnoreWatchPath(directory, ignoredPaths)) { + continue; + } + for (const entry of await readdir(directory, { withFileTypes: true })) { + const path = join(directory, entry.name); + if (shouldIgnoreWatchPath(path, ignoredPaths)) { + continue; + } + if (entry.isDirectory()) { + pending.push(path); + } else if (entry.isFile() && (entry.name.endsWith('.py') || entry.name.endsWith('.pyi'))) { + files.add(path); + } + } + } + } + + const hash = createHash('sha256'); + for (const file of [...files].sort()) { + const contents = await readFile(file); + hash.update(file); + hash.update('\0'); + hash.update(String(contents.length)); + hash.update('\0'); + hash.update(contents); + } + return hash.digest('hex'); +} + function isSameOrNestedPath(candidate: string, root: string): boolean { const resolvedCandidate = resolve(candidate); const resolvedRoot = resolve(root); @@ -606,6 +657,10 @@ async function resolveWatchTargets(config: TywrapOptions): Promise { const config = await resolveConfig({ configFile, requireConfig: true }); const watchTargets = await resolveWatchTargets(config); + const watchSources = normalizeWatchSources(watchTargets.map(toWatchSource)); + const outputDir = resolve(config.output.dir); + const ignoredPaths = buildIgnoredPaths(outputDir); + const sourceFingerprint = await fingerprintPythonSources(watchSources, ignoredPaths); const tempDir = await mkdtemp(join(tmpdir(), 'tywrap-dev-')); const stageOutputDir = join(tempDir, 'output'); @@ -632,8 +687,11 @@ async function generateToStage(configFile: string): Promise { files.set(relativePath, await readFile(writtenPath, 'utf-8')); } - const outputDir = resolve(config.output.dir); - const watchSources = normalizeWatchSources(watchTargets.map(toWatchSource)); + if ((await fingerprintPythonSources(watchSources, ignoredPaths)) !== sourceFingerprint) { + throw new Error( + 'Watched Python source changed during generation; keeping the current bridge' + ); + } return { config, @@ -643,6 +701,7 @@ async function generateToStage(configFile: string): Promise { warnings: result.warnings, failures: result.failures, watchSources, + sourceFingerprint, outputDir, }; } catch (error) { @@ -904,6 +963,13 @@ export async function startNodeWatchSession, - validate?: (result: T) => void + validate?: (result: T, provenance?: DecodedProvenance) => void ): Promise { await this.ensureReady(); return this.getRpcClient().call(module, functionName, args, kwargs, validate); diff --git a/src/runtime/bridge-codec.ts b/src/runtime/bridge-codec.ts index 2edc44bf..f0fc56f8 100644 --- a/src/runtime/bridge-codec.ts +++ b/src/runtime/bridge-codec.ts @@ -16,6 +16,7 @@ import { ScientificDecodeError, } from '../utils/codec.js'; import { PROTOCOL_ID } from './transport.js'; +import type { DecodedProvenance } from './decoded-provenance.js'; // ═══════════════════════════════════════════════════════════════════════════ // TYPES @@ -662,13 +663,13 @@ export class BridgeCodec { * @throws BridgeProtocolError if the RPC response is invalid * @throws BridgeExecutionError if response contains a Python error */ - async decodeResponseAsync(payload: string): Promise { + async decodeResponseAsync(payload: string, provenance?: DecodedProvenance): Promise { const result = this.parseResponseResult(payload); // Decode scientific envelopes in the result. let decoded: unknown; try { - decoded = await decodeScientificValue(result); + decoded = await decodeScientificValue(result, provenance); } catch (err) { const errorMessage = err instanceof Error ? err.message : String(err); const decodeError = err instanceof ScientificDecodeError ? err : undefined; diff --git a/src/runtime/decoded-provenance.ts b/src/runtime/decoded-provenance.ts new file mode 100644 index 00000000..945936af --- /dev/null +++ b/src/runtime/decoded-provenance.ts @@ -0,0 +1,72 @@ +import type { ScientificMarker } from '../utils/codec.js'; + +/** Metadata from one successfully decoded scientific envelope. */ +export interface DecodedShapeMetadata { + readonly marker: ScientificMarker; + readonly dims?: number; + readonly dtype?: string; +} + +/** Scalar provenance stays with one decoded call, including nested values. */ +export class DecodedProvenance { + private rootScalar?: DecodedShapeMetadata; + private readonly children = new WeakMap>(); + private entries = 0; + private readonly maxEntries: number; + + constructor(maxEntries = 1_000_000) { + if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) { + throw new Error('Decoded provenance entry limit must be a positive safe integer'); + } + this.maxEntries = maxEntries; + } + + recordRoot(metadata: DecodedShapeMetadata): void { + if (this.rootScalar !== undefined) { + throw new Error('Duplicate root scalar provenance'); + } + this.claimEntry(); + this.rootScalar = Object.freeze({ ...metadata }); + } + + recordChild(parent: object, key: string | number, metadata: DecodedShapeMetadata): void { + key = this.normalizeKey(parent, key); + let entries = this.children.get(parent); + if (!entries) { + entries = new Map(); + this.children.set(parent, entries); + } + if (entries.has(key)) { + throw new Error('Duplicate child scalar provenance'); + } + this.claimEntry(); + entries.set(key, Object.freeze({ ...metadata })); + } + + atRoot(): DecodedShapeMetadata | undefined { + return this.rootScalar; + } + + atChild(parent: object, key: string | number): DecodedShapeMetadata | undefined { + return this.children.get(parent)?.get(this.normalizeKey(parent, key)); + } + + private normalizeKey(parent: object, key: string | number): string | number { + if ( + Array.isArray(parent) && + typeof key === 'string' && + /^(0|[1-9]\d*)$/.test(key) && + Number.isSafeInteger(Number(key)) + ) { + return Number(key); + } + return key; + } + + private claimEntry(): void { + if (this.entries >= this.maxEntries) { + throw new Error(`Decoded scalar provenance exceeds ${this.maxEntries} entries`); + } + this.entries += 1; + } +} diff --git a/src/runtime/index.ts b/src/runtime/index.ts index c7f335ad..e19a87a7 100644 --- a/src/runtime/index.ts +++ b/src/runtime/index.ts @@ -13,7 +13,10 @@ import type { RuntimeExecution } from '../types/index.js'; export { BridgeCodec, type CodecOptions } from './bridge-codec.js'; export { createReturnValidator, + selectOverloadReturnValidator, describeReceivedShape, + type OverloadParameterSchema, + type OverloadReturnSchema, type ReturnSchema, type ReturnValidator, } from './validators.js'; diff --git a/src/runtime/pooled-transport.ts b/src/runtime/pooled-transport.ts index 4e6ccfc9..05b0b629 100644 --- a/src/runtime/pooled-transport.ts +++ b/src/runtime/pooled-transport.ts @@ -120,6 +120,10 @@ export class PooledTransport extends DisposableBase implements Transport { }; private readonly workers: TransportLease[] = []; private readonly waitQueue: QueuedWaiter[] = []; + private readonly retiringWorkers = new Set(); + private readonly retirements = new Set>(); + private retirementError?: Error; + private disposalInFlight?: Promise; /** Tracks workers being created to prevent race condition in acquire() */ private pendingCreations = 0; private cachedCapabilities?: TransportCapabilities; @@ -192,6 +196,24 @@ export class PooledTransport extends DisposableBase implements Transport { await this.fillToMinimumWorkers(); } + /** Retry retained worker cleanup after a failed disposal. */ + override dispose(): Promise { + if (this.disposalInFlight) { + return this.disposalInFlight; + } + const disposal = this.isDisposed ? this.retryRetiringWorkers() : super.dispose(); + this.disposalInFlight = disposal; + disposal.then( + () => { + this.disposalInFlight = undefined; + }, + () => { + this.disposalInFlight = undefined; + } + ); + return disposal; + } + /** * Dispose the pool and all workers. * @@ -207,17 +229,21 @@ export class PooledTransport extends DisposableBase implements Transport { } this.waitQueue.length = 0; - // Dispose all workers - const errors: Error[] = []; - for (const worker of this.workers) { + await Promise.all(this.retirements); + + // Retry cleanup for workers whose first disposal failed. + const errors = await this.cleanupRetiringWorkers(); + + // Dispose all active workers. + const activeWorkers = this.workers.splice(0); + for (const worker of activeWorkers) { try { await worker.transport.dispose(); } catch (e) { errors.push(e instanceof Error ? e : new Error(String(e))); + this.retiringWorkers.add(worker); } } - this.workers.length = 0; - // Report errors if any if (errors.length === 1) { throw errors[0]; @@ -244,6 +270,9 @@ export class PooledTransport extends DisposableBase implements Transport { * @throws BridgeExecutionError if pool is disposed while waiting */ async acquire(): Promise { + if (this.retirementError) { + throw this.retirementError; + } // Check for disposed state if (this.isDisposed || this.state === 'disposing') { throw new BridgeExecutionError('Pool has been disposed'); @@ -260,7 +289,10 @@ export class PooledTransport extends DisposableBase implements Transport { // Include pendingCreations to prevent race condition where multiple // concurrent acquire() calls all pass the length check before any // worker is actually added to the array - if (this.workers.length + this.pendingCreations < this.options.maxWorkers) { + if ( + this.workers.length + this.retiringWorkers.size + this.pendingCreations < + this.options.maxWorkers + ) { this.pendingCreations++; try { const newWorker = await this.createWorker(); @@ -329,6 +361,12 @@ export class PooledTransport extends DisposableBase implements Transport { } throw error; } finally { + // A subprocess may retire its process after this lease reached stdin. + // Remove it before another waiter can acquire the old generation. + if (!workerRemoved && this.requiresReplacement(worker)) { + this.removeWorker(worker); + workerRemoved = true; + } // Only release if worker wasn't removed due to fatal error if (!workerRemoved) { this.release(worker); @@ -362,24 +400,86 @@ export class PooledTransport extends DisposableBase implements Transport { return false; } + private requiresReplacement(worker: TransportLease): boolean { + const transport = worker.transport as Transport & { readonly requiresReplacement?: boolean }; + return transport.requiresReplacement === true; + } + /** * Remove a worker from the pool. * * This is called when a worker is detected as dead (crashed, pipe error, etc.). - * The worker's transport is disposed in the background. + * Hold its slot until disposal succeeds. Failed disposal blocks new leases. */ private removeWorker(worker: TransportLease): void { + if (this.state === 'disposing' || this.isDisposed) { + return; + } const index = this.workers.indexOf(worker); if (index !== -1) { this.workers.splice(index, 1); - // Dispose transport in background - don't await to avoid blocking - worker.transport.dispose().catch(() => { - // Ignore disposal errors for dead workers - }); - if (this.state === 'ready') { - this.scheduleReplacementWorker(); + this.retiringWorkers.add(worker); + const retirement = Promise.resolve() + .then(() => worker.transport.dispose()) + .then( + () => { + this.retiringWorkers.delete(worker); + if (this.state === 'ready') { + this.scheduleReplacementWorker(); + } + }, + error => { + this.recordCleanupFailure(error); + } + ) + .finally(() => { + this.retirements.delete(retirement); + }); + this.retirements.add(retirement); + } + } + + private async cleanupRetiringWorkers(): Promise { + const errors: Error[] = []; + for (const worker of this.retiringWorkers) { + try { + await worker.transport.dispose(); + this.retiringWorkers.delete(worker); + } catch (e) { + errors.push(e instanceof Error ? e : new Error(String(e))); } } + return errors; + } + + private async retryRetiringWorkers(): Promise { + const errors = await this.cleanupRetiringWorkers(); + if (errors.length === 1) { + throw errors[0]; + } + if (errors.length > 1) { + throw new AggregateError(errors, 'Multiple errors during worker disposal'); + } + } + + private recordCleanupFailure(error: unknown): Error { + const failure = error instanceof Error ? error : new Error(String(error)); + this.retirementError = failure; + for (const waiter of this.waitQueue) { + clearTimeout(waiter.timer); + waiter.reject(failure); + } + this.waitQueue.length = 0; + return failure; + } + + private async disposeUnpublishedWorker(worker: TransportLease): Promise { + try { + await worker.transport.dispose(); + } catch (error) { + this.retiringWorkers.add(worker); + throw this.recordCleanupFailure(error); + } } // =========================================================================== @@ -419,11 +519,15 @@ export class PooledTransport extends DisposableBase implements Transport { } private getMinimumWorkerDeficit(): number { - return Math.max(0, this.options.minWorkers - (this.workers.length + this.pendingCreations)); + return Math.max( + 0, + this.options.minWorkers - + (this.workers.length + this.retiringWorkers.size + this.pendingCreations) + ); } private isShuttingDown(): boolean { - return this.isDisposed || this.state === 'disposing'; + return this.isDisposed || this.state === 'disposing' || this.retirementError !== undefined; } private async fillToMinimumWorkers(): Promise { @@ -447,10 +551,13 @@ export class PooledTransport extends DisposableBase implements Transport { * the full worker cold-start penalty after a timeout or crash. */ private scheduleReplacementWorker(): void { - if (this.state !== 'ready') { + if (this.state !== 'ready' || this.retirementError) { return; } - if (this.workers.length + this.pendingCreations >= this.options.maxWorkers) { + if ( + this.workers.length + this.retiringWorkers.size + this.pendingCreations >= + this.options.maxWorkers + ) { return; } @@ -502,15 +609,22 @@ export class PooledTransport extends DisposableBase implements Transport { */ private async createWorker(onWorkerReady = this.options.onWorkerReady): Promise { const transport = this.options.createTransport(); - - // Initialize the transport - await transport.init(); - const worker: TransportLease = { transport, inFlightCount: 0, }; + try { + await transport.init(); + } catch (error) { + try { + await this.disposeUnpublishedWorker(worker); + } catch (cleanupError) { + throw new AggregateError([error, cleanupError], 'Worker init and cleanup failed'); + } + throw error; + } + try { // Call onWorkerReady callback if provided if (onWorkerReady) { @@ -518,16 +632,16 @@ export class PooledTransport extends DisposableBase implements Transport { } } catch (error) { // Ensure partially initialized workers do not leak when warmup fails. - await transport.dispose().catch(() => { - // Ignore disposal failures during warmup failure handling. - }); + try { + await this.disposeUnpublishedWorker(worker); + } catch (cleanupError) { + throw new AggregateError([error, cleanupError], 'Worker warmup and cleanup failed'); + } throw error; } - if (this.state === 'disposing' || this.state === 'disposed') { - await transport.dispose().catch(() => { - // Ignore disposal failures if the pool was torn down mid-creation. - }); + if (this.state === 'disposing' || this.state === 'disposed' || this.retirementError) { + await this.disposeUnpublishedWorker(worker); throw new BridgeExecutionError('Pool disposed during worker creation'); } diff --git a/src/runtime/pyodide-bootstrap-core.generated.ts b/src/runtime/pyodide-bootstrap-core.generated.ts index 68bb32c9..534e5425 100644 --- a/src/runtime/pyodide-bootstrap-core.generated.ts +++ b/src/runtime/pyodide-bootstrap-core.generated.ts @@ -9,4 +9,4 @@ * Regenerate with: node scripts/generate-pyodide-bootstrap.mjs */ -export const PYODIDE_BRIDGE_CORE_SOURCE: string = "\"\"\"\nShared tywrap bridge core: protocol dispatch + value (de)serialization.\n\nThis module is the SINGLE source of truth for the \"tywrap/1\" server-side\nprotocol. It is imported by:\n\n - runtime/python_bridge.py (the Node/Bun/Deno subprocess server and the HTTP\n server), which owns I/O concerns: the stdin/stdout JSONL loop, env-var size\n guards, the real OS pid, bridge='python-subprocess', and the final BridgeCodec\n encode wrapper.\n\n - the in-WASM Pyodide server (src/runtime/pyodide-transport.ts). Pyodide cannot read\n this file from disk, so it is shipped as a build-time-generated TypeScript\n string constant (src/runtime/pyodide-bootstrap-core.generated.ts) produced by\n scripts/generate-pyodide-bootstrap.mjs and exec'd into a module registered in\n sys.modules. A conformance drift guard (test/runtime_conformance.test.ts)\n asserts the generated constant stays byte-identical to this file.\n\nCROSS-LANGUAGE CONTRACT (Python <-> the TypeScript decoder in src/utils/codec.ts\nand the request encoder in src/runtime/bridge-codec.ts):\n\n * Every value-type \"marker\" envelope carries {'__tywrap__': ,\n 'codecVersion': 1, 'encoding': ...}. The 6 markers are: ndarray, dataframe,\n series, scipy.sparse, torch.tensor, sklearn.estimator.\n * bytes round-trip both ways via base64 envelopes (see _deserialize_bytes_*\n and the bytes branch of default_encoder).\n * NaN/Infinity are rejected (the JS client cannot parse the non-standard tokens\n that allow_nan=True would emit).\n\nPURITY: This module depends only on the standard library plus LAZY optional\nimports (numpy/pandas/scipy/torch/sklearn/pyarrow are each imported inside the\nfunction that needs them). It performs no stdin/stdout I/O and reads no env vars,\nso it runs unchanged under CPython-in-WASM (Pyodide).\n\nforce_json_markers: a *parameter* threaded through every serializer (including\nthe nested torch.tensor -> ndarray call). When True, ndarray/dataframe/series are\nforced down their JSON path regardless of pyarrow availability. Pyodide passes\nTrue (Arrow is unavailable in WASM); the subprocess server passes the boolean\nderived from TYWRAP_CODEC_FALLBACK=json so that \"Node in json-fallback mode\" and\n\"Pyodide\" produce byte-identical marker envelopes.\n\"\"\"\n\nimport base64\nimport datetime as dt\nimport decimal\nimport importlib\nimport importlib.util\nimport json\nimport math\nimport re\nimport sys\nimport traceback\nimport uuid\nfrom pathlib import Path, PurePath\n\n# Protocol constants. These MUST match src/runtime/protocol.ts (PROTOCOL_ID,\n# TYWRAP_PROTOCOL_VERSION) and the codec version baked into marker envelopes.\nPROTOCOL = 'tywrap/1'\nPROTOCOL_VERSION = 1\nCODEC_VERSION = 1\nMAX_SERIALIZE_DEPTH = 900\nMAX_SERIALIZE_NODES = 1_000_000\nJS_SAFE_INTEGER_MAX = 2**53 - 1\n_SERIALIZE_PATH_IDENTIFIER = re.compile(r'^[A-Za-z_$][\\w$]*$', re.ASCII)\n\n\nclass ProtocolError(Exception):\n \"\"\"Raised for malformed requests (bad protocol/id/method/params).\"\"\"\n\n\nclass ImportNotAllowedError(PermissionError):\n \"\"\"Raised when a requested module import is not on the active allowlist.\"\"\"\n\n def __init__(self, module_name):\n super().__init__(\n f'Import of module {module_name!r} is not permitted by the tywrap bridge '\n 'allowlist; add it to TYWRAP_ALLOWED_MODULES (subprocess) or the '\n 'allowed_modules parameter to enable it'\n )\n\n\nclass AttributeNotAllowedError(PermissionError):\n \"\"\"Raised when access to a private/dunder attribute is denied by policy.\"\"\"\n\n def __init__(self, attr_name):\n super().__init__(\n f'Access to attribute {attr_name!r} is not permitted by the tywrap bridge: '\n 'underscore-prefixed (private/dunder) attributes are blocked to prevent '\n 'sandbox-escape via attributes like __globals__/__subclasses__/__builtins__; '\n 'set TYWRAP_ALLOW_PRIVATE_ATTRS=1 (subprocess) or pass allow_private_attrs=True '\n 'to override'\n )\n\n\n# =============================================================================\n# IMPORT / ATTRIBUTE ALLOWLIST (trust boundary enforcement)\n# =============================================================================\n#\n# The bridge dispatches call requests by importing the requested module and\n# getattr-ing the requested function/class method. That is an\n# arbitrary import+getattr+call surface, so two complementary guards live here.\n# Both are PURE (no env reads) so the rules behave identically under the\n# subprocess server and the in-WASM Pyodide server; the subprocess server derives\n# the parameters from env vars (TYWRAP_ALLOWED_MODULES / TYWRAP_ALLOW_PRIVATE_ATTRS)\n# and threads them in, exactly like force_json_markers / torch_allow_copy.\n#\n# 1. MODULE ALLOWLIST (opt-in, default = allow all):\n# allowed_modules=None means \"no restriction\" so existing configurations keep\n# working unchanged. When a caller supplies a set, only those modules (plus the\n# stdlib the bridge itself needs to serialize results, see _BRIDGE_REQUIRED_MODULES)\n# may be imported; submodules of an allowed module are permitted (e.g. allowing\n# 'scipy' also allows 'scipy.sparse'). A non-allowlisted import fails LOUDLY with\n# ImportNotAllowedError rather than silently importing.\n#\n# 2. PRIVATE-ATTRIBUTE BLOCK (default ON):\n# getattr of any name starting with '_' (single-underscore private OR dunder) is\n# rejected. This blocks the classic escape chain (obj.__class__.__subclasses__()\n# /__globals__/__builtins__/__import__) without depending on the module allowlist.\n# tywrap-generated wrappers never reference underscore-prefixed names (the IR\n# analyzer skips them), so this does not regress generated code. Set\n# allow_private_attrs=True to restore unrestricted getattr for trusted callers.\n\n# Stdlib modules the bridge's own serialization/handlers may need to import even\n# when a caller-supplied allowlist is active. Optional codec deps (numpy, pandas,\n# scipy, torch, sklearn, pyarrow) are intentionally NOT here: if a caller restricts\n# modules, they must opt those in explicitly. These names cover only what the\n# bridge core itself imports.\n_BRIDGE_REQUIRED_MODULES = frozenset(\n {\n 'base64',\n 'datetime',\n 'decimal',\n 'importlib',\n 'json',\n 'math',\n 'sys',\n 'traceback',\n 'uuid',\n 'pathlib',\n }\n)\n\n\ndef _top_level_package(module_name):\n \"\"\"Return the top-level package of a dotted module name ('a.b.c' -> 'a').\"\"\"\n return module_name.split('.', 1)[0]\n\n\ndef _is_module_allowed(module_name, allowed_modules):\n \"\"\"\n Return True when module_name may be imported under the active policy.\n\n allowed_modules=None disables enforcement (allow all). Otherwise a module is\n allowed when it (or its top-level package) is explicitly listed, or it is one\n of the stdlib modules the bridge itself requires.\n \"\"\"\n if allowed_modules is None:\n return True\n if module_name in allowed_modules or module_name in _BRIDGE_REQUIRED_MODULES:\n return True\n top = _top_level_package(module_name)\n return top in allowed_modules or top in _BRIDGE_REQUIRED_MODULES\n\n\ndef import_allowed_module(module_name, allowed_modules):\n \"\"\"\n Import module_name only if permitted by the allowlist, else raise loudly.\n\n This is the single chokepoint every handler routes module imports through.\n \"\"\"\n if not _is_module_allowed(module_name, allowed_modules):\n raise ImportNotAllowedError(module_name)\n return importlib.import_module(module_name)\n\n\ndef get_allowed_attr(obj, attr_name, *, allow_private_attrs):\n \"\"\"\n getattr(obj, attr_name) with the private/dunder block applied.\n\n Rejects any underscore-prefixed name unless allow_private_attrs is True. This\n is the single chokepoint every handler routes attribute access through.\n \"\"\"\n if not allow_private_attrs and attr_name.startswith('_'):\n raise AttributeNotAllowedError(attr_name)\n return getattr(obj, attr_name)\n\n\ndef resolve_allowed_attr_path(root, dotted_name, *, allow_private_attrs):\n \"\"\"\n Resolve a possibly-dotted attribute path from root, applying the\n private/dunder getattr guard to EVERY segment.\n\n A single segment (the common case, e.g. a module-level function) behaves\n exactly like get_allowed_attr. Dotted names exist because @classmethod and\n @staticmethod are invoked through their owning class: the generated wrapper\n emits call(module, 'Class.method', ...), so the bridge must walk\n module -> Class -> method. Guarding each segment means 'Class._secret' or\n '_Hidden.method' are rejected exactly as a direct private getattr would be —\n the dotted path opens no access the single-getattr path did not already.\n \"\"\"\n obj = root\n for segment in dotted_name.split('.'):\n obj = get_allowed_attr(obj, segment, allow_private_attrs=allow_private_attrs)\n return obj\n\n\nclass CodecError(Exception):\n \"\"\"Raised when value encoding fails (e.g. NaN/Infinity not allowed).\"\"\"\n\n\n# =============================================================================\n# REQUEST-SIDE DESERIALIZATION (bytes envelopes -> Python bytes)\n# =============================================================================\n\n_NO_DESERIALIZE = object()\n_ERR_BYTES_MISSING_B64 = 'Invalid bytes envelope: missing b64'\n_ERR_BYTES_MISSING_DATA = 'Invalid bytes envelope: missing data'\n_ERR_BYTES_INVALID_BASE64 = 'Invalid bytes envelope: invalid base64'\n\n\ndef _deserialize_bytes_envelope(value):\n \"\"\"\n Decode base64-encoded bytes envelopes from JS into Python bytes.\n\n Supported shapes:\n - { \"__tywrap_bytes__\": true, \"b64\": \"...\" } (JS BridgeCodec.encodeRequest)\n - { \"__type__\": \"bytes\", \"encoding\": \"base64\", \"data\": \"...\" } (legacy/compat)\n\n Why: TS BridgeCodec encodes Uint8Array/ArrayBuffer as base64 objects, but\n Python handlers expect real bytes/bytearray to preserve behavior (e.g., len()).\n \"\"\"\n if not isinstance(value, dict):\n return _NO_DESERIALIZE\n\n if value.get('__tywrap_bytes__') is True:\n b64 = value.get('b64')\n if not isinstance(b64, str):\n raise ProtocolError(_ERR_BYTES_MISSING_B64)\n try:\n return base64.b64decode(b64, validate=True)\n except Exception as exc:\n raise ProtocolError(_ERR_BYTES_INVALID_BASE64) from exc\n\n if value.get('__type__') == 'bytes' and value.get('encoding') == 'base64':\n data = value.get('data')\n if not isinstance(data, str):\n raise ProtocolError(_ERR_BYTES_MISSING_DATA)\n try:\n return base64.b64decode(data, validate=True)\n except Exception as exc:\n raise ProtocolError(_ERR_BYTES_INVALID_BASE64) from exc\n\n return _NO_DESERIALIZE\n\n\ndef deserialize(value, *, has_envelope_markers=True):\n \"\"\"\n Recursively deserialize request values into Python-native types.\n\n Why: requests are JSON-only; we need a small set of explicit decoders\n (currently bytes) to restore Python semantics at the boundary.\n \"\"\"\n if not has_envelope_markers:\n return value\n decoded = _deserialize_bytes_envelope(value)\n if decoded is not _NO_DESERIALIZE:\n return decoded\n\n if isinstance(value, list):\n return [deserialize(item, has_envelope_markers=True) for item in value]\n if isinstance(value, dict):\n # Preserve dict shape while decoding nested values.\n return {k: deserialize(v, has_envelope_markers=True) for k, v in value.items()}\n return value\n\n\n# =============================================================================\n# CAPABILITY DETECTION (lazy, best-effort)\n# =============================================================================\n\ndef arrow_available():\n \"\"\"Return True when pyarrow can be imported.\"\"\"\n try:\n import pyarrow # noqa: F401\n except (ImportError, OSError):\n return False\n return True\n\n\ndef module_available(module_name):\n \"\"\"\n Lightweight feature detection for optional codec dependencies via find_spec.\n\n Why: exposes availability in bridge metadata without importing heavy modules.\n \"\"\"\n try:\n return importlib.util.find_spec(module_name) is not None\n except (ImportError, AttributeError, TypeError, ValueError):\n return False\n\n\ndef is_numpy_array(obj):\n \"\"\"Return whether obj is an ndarray without importing NumPy.\"\"\"\n np = sys.modules.get('numpy')\n if np is None:\n return False\n return isinstance(obj, np.ndarray)\n\n\ndef is_pandas_dataframe(obj):\n \"\"\"Return whether obj is a DataFrame without importing pandas.\"\"\"\n pd = sys.modules.get('pandas')\n if pd is None:\n return False\n return isinstance(obj, pd.DataFrame)\n\n\ndef is_pandas_series(obj):\n \"\"\"Return whether obj is a Series without importing pandas.\"\"\"\n pd = sys.modules.get('pandas')\n if pd is None:\n return False\n return isinstance(obj, pd.Series)\n\n\ndef is_scipy_sparse(obj):\n \"\"\"Return whether obj is sparse without importing SciPy.\"\"\"\n sp = sys.modules.get('scipy.sparse')\n if sp is None:\n return False\n try:\n return sp.issparse(obj)\n except Exception:\n return False\n\n\ndef is_torch_tensor(obj):\n \"\"\"Return whether obj is a Tensor without importing PyTorch.\"\"\"\n torch = sys.modules.get('torch')\n if torch is None:\n return False\n try:\n return torch.is_tensor(obj)\n except Exception:\n return False\n\n\ndef is_sklearn_estimator(obj):\n \"\"\"Return whether obj is an estimator without importing scikit-learn.\"\"\"\n sklearn_base = sys.modules.get('sklearn.base')\n if sklearn_base is None:\n return False\n return isinstance(obj, sklearn_base.BaseEstimator)\n\n\n# =============================================================================\n# MARKER SERIALIZERS (6 __tywrap__ value types)\n# =============================================================================\n#\n# Each serializer accepts force_json_markers. When True, the Arrow path is never\n# taken (used by Pyodide and by the subprocess server in TYWRAP_CODEC_FALLBACK=json\n# mode). The JSON fallback envelopes are byte-identical across both callers, which\n# is what the conformance suite asserts.\n\ndef serialize_ndarray(obj, *, force_json_markers):\n \"\"\"\n Encode a NumPy ndarray. Arrow IPC (compact, lossless) by default; JSON when\n force_json_markers is set or pyarrow is unavailable in fallback mode.\n\n Note: pa.array() only handles 1D arrays; multi-dimensional arrays are\n flattened with shape metadata for JS-side reconstruction. See\n https://github.com/apache/arrow-js/issues/115\n \"\"\"\n if force_json_markers:\n return serialize_ndarray_json(obj)\n try:\n import pyarrow as pa # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for ndarray; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n original_shape = list(obj.shape) if hasattr(obj, 'shape') else None\n flat = obj.flatten() if hasattr(obj, 'ndim') and obj.ndim != 1 else obj\n arr = pa.array(flat)\n table = pa.Table.from_arrays([arr], names=['value'])\n sink = pa.BufferOutputStream()\n with pa.ipc.new_stream(sink, table.schema) as writer:\n writer.write_table(table)\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'ndarray',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n 'shape': original_shape,\n 'dtype': str(obj.dtype) if hasattr(obj, 'dtype') else None,\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for ndarray') from exc\n\n\ndef serialize_ndarray_json(obj):\n \"\"\"JSON fallback for ndarray values that JavaScript can represent safely.\"\"\"\n dtype = obj.dtype\n dtype_label = str(dtype)\n\n if not dtype.isnative:\n raise RuntimeError(\n f'JSON ndarray encoding does not support big-endian dtype={dtype_label}; '\n \"convert to native byte order with a.byteswap().view(a.dtype.newbyteorder('='))\"\n )\n\n if dtype.kind in ('i', 'u'):\n # JSON numbers become JavaScript Number values. Scan only on this explicit\n # fallback path and reject before tolist() can silently round an integer.\n if obj.size and (\n (obj < -JS_SAFE_INTEGER_MAX).any() or (obj > JS_SAFE_INTEGER_MAX).any()\n ):\n raise RuntimeError(\n f'JSON ndarray encoding cannot safely represent dtype={dtype_label} values '\n 'outside the JavaScript safe integer range; use Arrow encoding or '\n \"cast/encode explicitly (e.g. .astype('float64') or str)\"\n )\n elif dtype.kind == 'M':\n raise RuntimeError(\n f'JSON ndarray encoding does not support dtype={dtype_label}; use Arrow encoding '\n \"or convert explicitly (e.g. .astype('datetime64[ms]').astype(str) or int with \"\n 'declared unit)'\n )\n elif dtype.kind == 'm':\n raise RuntimeError(\n f'JSON ndarray encoding does not support dtype={dtype_label}; use Arrow encoding '\n \"or convert explicitly (e.g. .astype('timedelta64[ms]').astype(str) or int with \"\n 'declared unit)'\n )\n elif dtype.kind == 'V':\n if dtype.fields is not None:\n raise RuntimeError(\n f'JSON ndarray encoding does not support structured dtype={dtype_label}; '\n 'encode each named field explicitly (e.g. as a plain JSON object)'\n )\n raise RuntimeError(\n f'JSON ndarray encoding does not support void dtype={dtype_label}; convert the '\n \"raw bytes explicitly (e.g. .view('uint8'))\"\n )\n elif dtype.kind == 'O':\n raise RuntimeError(\n f'JSON ndarray encoding does not support object dtype={dtype_label}; cast to a '\n 'concrete numeric dtype or encode elements explicitly as plain JSON'\n )\n elif dtype.kind == 'S':\n raise RuntimeError(\n f'JSON ndarray encoding does not support byte-string dtype={dtype_label}; '\n 'decode elements and return a plain JSON list explicitly'\n )\n elif dtype.kind == 'U':\n raise RuntimeError(\n f'JSON ndarray encoding does not support unicode dtype={dtype_label}; convert '\n 'explicitly to plain JSON strings with .tolist()'\n )\n elif dtype.kind == 'c':\n raise RuntimeError(\n f'JSON ndarray encoding does not support complex dtype={dtype_label}; encode '\n '.real and .imag arrays explicitly'\n )\n elif dtype.kind == 'f' and dtype.itemsize > 8:\n raise RuntimeError(\n f'JSON ndarray encoding does not support float dtype={dtype_label} wider than '\n \"64 bits; cast explicitly (e.g. .astype('float64')) or use Arrow encoding\"\n )\n elif dtype.kind not in ('b', 'f'):\n raise RuntimeError(\n f'JSON ndarray encoding does not support dtype={dtype_label}; cast to bool, '\n 'integer, or float dtype, or encode values explicitly as plain JSON'\n )\n\n try:\n data = obj.tolist()\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for ndarray') from exc\n return {\n '__tywrap__': 'ndarray',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n 'shape': getattr(obj, 'shape', None),\n 'dtype': dtype.name,\n }\n\n\ndef serialize_dataframe(obj, *, force_json_markers):\n \"\"\"\n Encode a pandas DataFrame. Feather/Arrow-IPC (uncompressed, so apache-arrow\n in JS can read it) by default; JSON when force_json_markers is set.\n \"\"\"\n if force_json_markers:\n return serialize_dataframe_json(obj)\n try:\n import pyarrow as pa # type: ignore\n import pyarrow.feather as feather # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for pandas.DataFrame; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n table = pa.Table.from_pandas(obj) # type: ignore\n sink = pa.BufferOutputStream()\n feather.write_feather(table, sink, compression='uncompressed')\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'dataframe',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for pandas.DataFrame') from exc\n\n\ndef serialize_dataframe_json(obj):\n \"\"\"JSON fallback for DataFrame values that JavaScript can represent safely.\"\"\"\n import pandas as pd # type: ignore\n\n _validate_pandas_json_index(obj.index, pd, 'DataFrame')\n json_columns = [_json_object_key(column) for column in obj.columns]\n supported_json_columns = [column for column in json_columns if column is not None]\n if not obj.columns.is_unique or len(set(supported_json_columns)) != len(\n supported_json_columns\n ):\n raise RuntimeError(\n 'JSON pandas.DataFrame encoding requires column labels to remain unique after '\n 'JSON object-key coercion; rename columns or make them distinct before applying '\n '.columns.astype(str)'\n )\n for column, dtype in obj.dtypes.items():\n if isinstance(dtype, pd.CategoricalDtype):\n raise RuntimeError(\n f'JSON pandas.DataFrame encoding does not support categorical dtype in '\n f'column {column!r}; use Arrow encoding or convert explicitly '\n \"(e.g. .astype(str))\"\n )\n try:\n data = (\n [{} for _ in range(len(obj.index))]\n if len(obj.columns) == 0\n else obj.to_dict(orient='records')\n )\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for pandas.DataFrame') from exc\n for row_number, row in enumerate(data):\n for column, value in row.items():\n row[column] = _normalize_pandas_json_scalar(\n value,\n f'DataFrame cell at row {row_number}, column {column!r}',\n pd,\n )\n return {\n '__tywrap__': 'dataframe',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n }\n\n\ndef serialize_series(obj, *, force_json_markers):\n \"\"\"\n Encode a pandas Series as a single-column Arrow Table stream (the JS decoder\n contract is \"table-like\"); JSON when force_json_markers is set.\n \"\"\"\n if force_json_markers:\n return serialize_series_json(obj)\n try:\n import pyarrow as pa # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for pandas.Series; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n arr = pa.Array.from_pandas(obj) # type: ignore\n table = pa.Table.from_arrays([arr], names=['value'])\n sink = pa.BufferOutputStream()\n with pa.ipc.new_stream(sink, table.schema) as writer:\n writer.write_table(table)\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'series',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n 'name': getattr(obj, 'name', None),\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for pandas.Series') from exc\n\n\ndef serialize_series_json(obj):\n \"\"\"JSON fallback for Series values that JavaScript can represent safely.\"\"\"\n import pandas as pd # type: ignore\n\n _validate_pandas_json_index(obj.index, pd, 'Series')\n if isinstance(obj.dtype, pd.CategoricalDtype):\n raise RuntimeError(\n 'JSON pandas.Series encoding does not support categorical dtype; use Arrow '\n \"encoding or convert explicitly (e.g. .astype(str))\"\n )\n try:\n data = obj.to_list() # type: ignore\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for pandas.Series') from exc\n data = [\n _normalize_pandas_json_scalar(value, f'Series value at position {position}', pd)\n for position, value in enumerate(data)\n ]\n return {\n '__tywrap__': 'series',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n 'name': getattr(obj, 'name', None),\n }\n\n\ndef _validate_pandas_json_index(index, pd, container_name):\n \"\"\"Reject index metadata that records/list-oriented JSON would discard.\"\"\"\n if isinstance(index, pd.MultiIndex):\n raise RuntimeError(\n f'JSON pandas.{container_name} encoding does not support MultiIndex; use Arrow '\n 'encoding or flatten the index explicitly with .reset_index()'\n )\n if not (\n isinstance(index, pd.RangeIndex)\n and index.start == 0\n and index.step == 1\n and index.stop == len(index)\n and index.name is None\n ):\n raise RuntimeError(\n f'JSON pandas.{container_name} encoding requires an unnamed RangeIndex starting '\n 'at 0 with step 1; use Arrow encoding or normalize explicitly with '\n '.reset_index(drop=True)'\n )\n\n\ndef _json_object_key(value):\n \"\"\"Return json.dumps' object-key spelling, or None for unsupported keys.\"\"\"\n try:\n encoded = json.dumps({value: None})\n except (TypeError, ValueError):\n return None\n return next(iter(json.loads(encoded)))\n\n\ndef _normalize_pandas_json_scalar(value, location, pd):\n \"\"\"Normalize pandas nulls and reject values outside the plain JSON domain.\"\"\"\n np = sys.modules.get('numpy')\n if np is not None and isinstance(value, np.generic):\n value = value.item()\n if value is None or value is pd.NA or value is pd.NaT:\n return None\n if type(value) is bool:\n return value\n if type(value) is int:\n if value < -JS_SAFE_INTEGER_MAX or value > JS_SAFE_INTEGER_MAX:\n raise RuntimeError(\n f'JSON pandas encoding cannot safely represent {location} integer values '\n 'outside the JavaScript safe integer range; use Arrow encoding or '\n \"cast/encode explicitly (e.g. .astype('float64') or str)\"\n )\n return value\n if type(value) is float:\n if not math.isfinite(value):\n raise RuntimeError(\n f'JSON pandas encoding cannot represent non-finite {location} float values '\n '(NaN or Infinity); use .fillna(...) for intentional missing values or '\n 'Arrow encoding'\n )\n return value\n if type(value) is str:\n return value\n raise RuntimeError(\n f'JSON pandas encoding does not support {location} value of type '\n f'{type(value).__name__}; use Arrow encoding or convert explicitly '\n '(e.g. .astype(str))'\n )\n\n\ndef serialize_sparse_matrix(obj):\n \"\"\"\n Serialize scipy sparse matrices into structured JSON envelopes (json-only;\n there is no Arrow path). Preserves sparsity; rejects unsupported formats and\n complex dtypes explicitly.\n \"\"\"\n try:\n fmt = obj.getformat()\n except Exception as exc:\n raise RuntimeError('Failed to inspect scipy sparse matrix format') from exc\n\n if fmt not in ('csr', 'csc', 'coo'):\n raise RuntimeError(\n f'Unsupported scipy sparse format: {fmt}; only csr/csc/coo are supported. '\n 'Convert explicitly (e.g. matrix.tocsr()) before returning'\n )\n\n dtype = None\n try:\n dtype = str(obj.dtype)\n except Exception:\n dtype = None\n if getattr(obj.dtype, 'kind', None) == 'c':\n raise RuntimeError(\n 'Complex scipy sparse matrices are not supported by the JSON codec; '\n 'split into real/imag components explicitly before returning'\n )\n\n if fmt in ('csr', 'csc'):\n data = obj.data.tolist()\n indices = obj.indices.tolist()\n indptr = obj.indptr.tolist()\n return {\n '__tywrap__': 'scipy.sparse',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'format': fmt,\n 'shape': list(obj.shape),\n 'data': data,\n 'indices': indices,\n 'indptr': indptr,\n 'dtype': dtype,\n }\n\n # coo\n data = obj.data.tolist()\n row = obj.row.tolist()\n col = obj.col.tolist()\n return {\n '__tywrap__': 'scipy.sparse',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'format': fmt,\n 'shape': list(obj.shape),\n 'data': data,\n 'row': row,\n 'col': col,\n 'dtype': dtype,\n }\n\n\ndef serialize_torch_tensor(obj, *, force_json_markers, torch_allow_copy=False):\n \"\"\"\n Serialize torch.Tensor values via the nested ndarray envelope. CPU-only by\n default; device/copy behavior is explicit. force_json_markers is threaded\n into the nested ndarray serialization so Pyodide gets a JSON ndarray value.\n\n Rejection order is significant: the categorical rejections (sparse / quantized\n / meta / complex) are checked BEFORE the device/contiguous opt-in branch so\n they fail with a clear, specific message and are NOT bypassable by\n TYWRAP_TORCH_ALLOW_COPY. The opt-in only governs the device transfer and\n contiguous copy, never an unrepresentable layout/dtype.\n \"\"\"\n import torch # already importable: is_torch_tensor() gated the dispatch\n\n tensor = obj.detach()\n source_device = None\n source_dtype = None\n\n # Sparse tensors (COO/CSR/CSC/BSR/BSC -> any non-strided layout) have no dense\n # numpy representation without a densify step, which is not the round-trip this\n # envelope promises. Reject explicitly rather than emitting a misleading\n # \"not contiguous\" error or silently densifying.\n layout = getattr(tensor, 'layout', None)\n if getattr(tensor, 'is_sparse', False) or (\n layout is not None and layout != torch.strided\n ):\n raise RuntimeError(\n f'Torch sparse tensors are not supported (layout={layout}); '\n 'convert to a dense CPU tensor explicitly (e.g. tensor.to_dense()) before returning'\n )\n\n # Quantized tensors carry a qscheme/scale/zero_point that numpy() cannot\n # represent; .numpy() raises an opaque \"unsupported ScalarType\" deep in torch.\n # Reject up front with an actionable message.\n if getattr(tensor, 'is_quantized', False):\n raise RuntimeError(\n 'Torch quantized tensors are not supported; dequantize explicitly '\n '(e.g. tensor.dequantize()) before returning'\n )\n\n # Meta tensors have shape/dtype but NO storage; copying to CPU yields garbage,\n # so this is never a lossy-but-honest transfer the opt-in could authorize.\n if getattr(tensor, 'is_meta', False) or (\n getattr(tensor, 'device', None) is not None and tensor.device.type == 'meta'\n ):\n raise RuntimeError(\n 'Torch meta tensors carry no data and cannot be serialized; '\n 'materialize the tensor on a real device before returning'\n )\n\n # Complex tensors round-trip to numpy complex arrays, which are not\n # JSON-serializable and have no codec envelope. Reject explicitly instead of\n # emitting Python complex tuples that the JS decoder cannot parse.\n if torch.is_complex(tensor):\n raise RuntimeError(\n f'Torch complex tensors are not supported (dtype={tensor.dtype}); '\n 'split into real/imag components explicitly before returning'\n )\n\n if getattr(tensor, 'device', None) is not None and tensor.device.type != 'cpu':\n if not torch_allow_copy:\n raise RuntimeError(\n 'Torch tensor is on a non-CPU device; set TYWRAP_TORCH_ALLOW_COPY=1 to allow CPU transfer'\n )\n source_device = str(tensor.device)\n tensor = tensor.to('cpu')\n if hasattr(tensor, 'is_contiguous') and not tensor.is_contiguous():\n if not torch_allow_copy:\n raise RuntimeError(\n 'Torch tensor is not contiguous; set TYWRAP_TORCH_ALLOW_COPY=1 to allow contiguous copy'\n )\n tensor = tensor.contiguous()\n if tensor.dtype == torch.bfloat16:\n source_dtype = str(tensor.dtype)\n tensor = tensor.float()\n try:\n arr = tensor.numpy()\n except Exception as exc:\n raise RuntimeError('Failed to convert torch.Tensor to numpy') from exc\n\n envelope = {\n '__tywrap__': 'torch.tensor',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'ndarray',\n 'value': serialize_ndarray(arr, force_json_markers=force_json_markers),\n 'shape': list(tensor.shape),\n 'dtype': str(tensor.dtype),\n 'device': str(tensor.device),\n }\n if source_dtype is not None:\n envelope['sourceDtype'] = source_dtype\n if source_device is not None:\n envelope['sourceDevice'] = source_device\n return envelope\n\n\ndef serialize_sklearn_estimator(obj):\n \"\"\"Serialize sklearn estimators as metadata only (json-only); no pickling.\"\"\"\n try:\n import sklearn # noqa: F401\n except Exception as exc:\n raise RuntimeError('scikit-learn is not available') from exc\n\n params = obj.get_params(deep=False)\n\n # Metadata-only: NEVER pickle/joblib. Every param value must be plain JSON\n # (no callables, nested estimators, numpy arrays, or other objects). Probe\n # each value individually so the error names the offending param instead of\n # failing opaquely on the whole dict. allow_nan=False also rejects NaN/Inf\n # params here for parity with the response codec.\n for key, value in params.items():\n try:\n json.dumps(value, allow_nan=False)\n except (TypeError, ValueError) as exc:\n raise RuntimeError(\n f'scikit-learn estimator param {key!r} is not JSON-serializable '\n f'(got {type(value).__name__}); estimators are serialized as metadata only '\n '(no pickle/joblib), so every param must be a plain JSON value. '\n 'Sanitize or drop the param before returning'\n ) from exc\n\n return {\n '__tywrap__': 'sklearn.estimator',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'className': obj.__class__.__name__,\n 'module': obj.__class__.__module__,\n 'version': getattr(sklearn, '__version__', None),\n 'params': params,\n }\n\n\n_NO_PYDANTIC = object()\n\n\ndef serialize_pydantic(obj):\n \"\"\"\n Serialize Pydantic v2 models via model_dump(by_alias=True, mode='json')\n without importing Pydantic. Returns _NO_PYDANTIC when obj is not a model.\n \"\"\"\n model_dump = getattr(obj, 'model_dump', None)\n if not callable(model_dump):\n return _NO_PYDANTIC\n try:\n try:\n return model_dump(by_alias=True, mode='json')\n except TypeError:\n # Older Pydantic versions may not support `mode=...`.\n return model_dump(by_alias=True)\n except Exception as exc:\n raise RuntimeError(f'model_dump failed: {exc}') from exc\n\n\ndef serialize_stdlib(obj):\n \"\"\"Coerce common stdlib scalar types to JSON-safe forms; None otherwise.\"\"\"\n if isinstance(obj, dt.datetime):\n return obj.isoformat()\n if isinstance(obj, dt.date):\n return obj.isoformat()\n if isinstance(obj, dt.time):\n return obj.isoformat()\n if isinstance(obj, dt.timedelta):\n return obj.total_seconds()\n if isinstance(obj, decimal.Decimal):\n return str(obj)\n if isinstance(obj, uuid.UUID):\n return str(obj)\n if isinstance(obj, (Path, PurePath)):\n return str(obj)\n return None\n\n\n_NO_SCIENTIFIC = object()\n\n\ndef _check_serialize_depth(depth, path):\n if depth > MAX_SERIALIZE_DEPTH:\n raise RuntimeError(\n f'Scientific envelope serialization maximum depth '\n f'{MAX_SERIALIZE_DEPTH} exceeded at {path}'\n )\n\n\ndef _check_serialize_nodes(nodes, path):\n if nodes > MAX_SERIALIZE_NODES:\n raise RuntimeError(\n f'Scientific envelope serialization maximum visited nodes '\n f'{MAX_SERIALIZE_NODES} exceeded at {path}'\n )\n\n\ndef _serialize_scientific(obj, *, force_json_markers, torch_allow_copy, depth, path):\n \"\"\"Serialize a supported scientific value, or return _NO_SCIENTIFIC.\"\"\"\n package = type(obj).__module__.split('.', 1)[0]\n\n if package == 'numpy' and 'numpy' in sys.modules:\n if is_numpy_array(obj):\n _check_serialize_depth(depth, path)\n return serialize_ndarray(obj, force_json_markers=force_json_markers)\n elif package == 'pandas' and 'pandas' in sys.modules:\n if is_pandas_dataframe(obj):\n _check_serialize_depth(depth, path)\n return serialize_dataframe(obj, force_json_markers=force_json_markers)\n if is_pandas_series(obj):\n _check_serialize_depth(depth, path)\n return serialize_series(obj, force_json_markers=force_json_markers)\n elif package == 'scipy' and 'scipy.sparse' in sys.modules:\n if is_scipy_sparse(obj):\n _check_serialize_depth(depth, path)\n return serialize_sparse_matrix(obj)\n elif package == 'torch' and 'torch' in sys.modules:\n if is_torch_tensor(obj):\n _check_serialize_depth(depth, path)\n _check_serialize_depth(depth + 1, _serialize_path(path, 'value'))\n return serialize_torch_tensor(\n obj, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy\n )\n elif 'sklearn.base' in sys.modules and is_sklearn_estimator(obj):\n # No package gate here, unlike the branches above: subclassing\n # BaseEstimator is sklearn's documented extension point, so user-defined\n # estimators live outside the 'sklearn' package and must still get the\n # estimator serializer (and its param-naming errors).\n _check_serialize_depth(depth, path)\n return serialize_sklearn_estimator(obj)\n\n return _NO_SCIENTIFIC\n\n\ndef _serialize_path(base, key):\n \"\"\"Build a decoder-compatible JSONPath-like result path.\"\"\"\n if isinstance(key, int):\n return f'{base}[{key}]'\n if _SERIALIZE_PATH_IDENTIFIER.fullmatch(key):\n return f'{base}.{key}'\n return f'{base}[{json.dumps(key, ensure_ascii=False)}]'\n\n\ndef _invalid_key_path(base, key):\n \"\"\"Name a dict key that cannot be represented by JSON.\"\"\"\n return f'{base}[{key!r}]'\n\n\ndef _needs_serialize_visit(value):\n \"\"\"Return whether value needs container or scientific traversal work.\"\"\"\n if type(value) in (type(None), bool, int, float, str):\n return False\n if type(value) in (dict, list, tuple):\n return True\n package = type(value).__module__.split('.', 1)[0]\n if package in ('numpy', 'pandas', 'scipy', 'torch'):\n return True\n return 'sklearn.base' in sys.modules and is_sklearn_estimator(value)\n\n\ndef _serialize_leaf(value):\n \"\"\"Apply non-container conversions without allocating a traversal frame.\"\"\"\n if type(value) in (type(None), bool, int, float, str):\n return value\n pydantic_value = serialize_pydantic(value)\n if pydantic_value is not _NO_PYDANTIC:\n return pydantic_value\n stdlib_value = serialize_stdlib(value)\n if stdlib_value is not None:\n return stdlib_value\n return value\n\n\ndef serialize(obj, *, force_json_markers, torch_allow_copy=False):\n \"\"\"\n Top-level result serializer.\n\n Scientific codecs are type-first and only inspect packages that the value can\n belong to. A value from an optional package implies that package is already in\n sys.modules, so these checks never cold-import the scientific stack. The\n package dispatch deliberately precedes the JSON-native fast path: e.g. a\n package-defined subclass of dict still receives its relevant codec check.\n Every other value is left untouched so the shared JSON encoder applies the\n exact same default conversion at the root and at any nested depth.\n \"\"\"\n root = [None]\n active_ids = set()\n stack = [('visit', obj, 0, 'result', root, 0)]\n visited_nodes = 0\n\n # Repeated aliases have value semantics and are intentionally serialized twice.\n while stack:\n frame = stack.pop()\n action = frame[0]\n if action == 'dict':\n _, current, depth, path, parent, key, output, iterator = frame\n try:\n item_key, item = next(iterator)\n except StopIteration:\n active_ids.remove(id(current))\n parent[key] = output\n continue\n stack.append(frame)\n if not (isinstance(item_key, (str, int, float, bool)) or item_key is None):\n invalid_path = _invalid_key_path(path, item_key)\n raise TypeError(\n f'keys must be str, int, float, bool or None, not '\n f'{type(item_key).__name__} at {invalid_path}'\n )\n child_key = _json_object_key(item_key)\n child_path = _serialize_path(path, child_key)\n if _needs_serialize_visit(item):\n stack.append(('visit', item, depth + 1, child_path, output, item_key))\n else:\n output[item_key] = _serialize_leaf(item)\n continue\n if action == 'sequence':\n _, current, depth, path, parent, key, output, index = frame\n if index == len(output):\n active_ids.remove(id(current))\n parent[key] = output if type(current) is list else tuple(output)\n continue\n stack.append(('sequence', current, depth, path, parent, key, output, index + 1))\n item = current[index]\n if _needs_serialize_visit(item):\n stack.append(\n ('visit', item, depth + 1, _serialize_path(path, index), output, index)\n )\n else:\n output[index] = _serialize_leaf(item)\n continue\n\n _, current, depth, path, parent, key = frame\n try:\n scientific = _serialize_scientific(\n current,\n force_json_markers=force_json_markers,\n torch_allow_copy=torch_allow_copy,\n depth=depth,\n path=path,\n )\n except Exception as exc:\n if path == 'result':\n raise\n raise RuntimeError(f'Scientific value serialization failed at {path}: {exc}') from exc\n if scientific is not _NO_SCIENTIFIC:\n # Recognized envelopes are terminal containers to the JS decoder.\n visited_nodes += 1\n _check_serialize_nodes(visited_nodes, path)\n if scientific.get('__tywrap__') == 'torch.tensor':\n nested_path = _serialize_path(path, 'value')\n try:\n visited_nodes += 1\n _check_serialize_nodes(visited_nodes, nested_path)\n except Exception as exc:\n if path == 'result':\n raise\n raise RuntimeError(\n f'Scientific value serialization failed at {path}: {exc}'\n ) from exc\n parent[key] = scientific\n continue\n\n container_type = type(current)\n if container_type in (dict, list, tuple):\n _check_serialize_depth(depth, path)\n visited_nodes += 1\n _check_serialize_nodes(visited_nodes, path)\n current_id = id(current)\n if current_id in active_ids:\n raise RuntimeError(f'Circular reference detected at {path}')\n active_ids.add(current_id)\n\n if container_type is dict:\n output = {}\n parent[key] = output\n stack.append(\n ('dict', current, depth, path, parent, key, output, iter(current.items()))\n )\n continue\n\n output = [None] * len(current)\n if container_type is list:\n parent[key] = output\n stack.append(('sequence', current, depth, path, parent, key, output, 0))\n continue\n\n parent[key] = _serialize_leaf(current)\n\n return root[0]\n\n\n# =============================================================================\n# JSON CODEC: value handling and size-limited encode/decode\n# =============================================================================\n#\n# This is the single Python implementation used by both the subprocess bridge and\n# the embedded Pyodide core. BridgeCodec adds payload-size enforcement around the\n# shared encoder; encode_value is the unbounded form used by the in-memory bridge.\n\ndef _is_nan_or_inf(value):\n if not isinstance(value, (int, float)):\n return False\n try:\n return math.isnan(value) or math.isinf(value)\n except (TypeError, ValueError):\n return False\n\n\ndef _is_numpy_scalar(obj):\n try:\n import numpy as np\n except ImportError:\n return False\n return isinstance(obj, (np.generic, np.ndarray)) and obj.ndim == 0\n\n\ndef _is_pandas_scalar(obj):\n try:\n import pandas as pd\n except ImportError:\n return False\n return isinstance(obj, (pd.Timestamp, pd.Timedelta, type(pd.NaT)))\n\n\ndef make_default_encoder(*, allow_nan):\n \"\"\"\n Build a json.dumps default= encoder matching BridgeCodec's value handling.\n\n Raises CodecError for NaN/Infinity extracted from numpy scalars (json.dumps\n itself rejects top-level/nested NaN/Infinity floats when allow_nan=False).\n \"\"\"\n\n def default_encoder(obj):\n # numpy/pandas scalars first (need .item() extraction).\n if _is_numpy_scalar(obj):\n extracted = obj.item()\n if not allow_nan and _is_nan_or_inf(extracted):\n raise CodecError('Cannot serialize NaN - NaN/Infinity not allowed in JSON')\n return extracted\n\n if _is_pandas_scalar(obj):\n try:\n import pandas as pd\n except ImportError:\n pass\n else:\n if obj is pd.NaT or (hasattr(pd, 'isna') and pd.isna(obj)):\n return None\n if isinstance(obj, pd.Timestamp):\n return obj.isoformat()\n if isinstance(obj, pd.Timedelta):\n return obj.total_seconds()\n\n stdlib_value = serialize_stdlib(obj)\n if stdlib_value is not None:\n return stdlib_value\n\n if isinstance(obj, (bytes, bytearray)):\n return {\n '__type__': 'bytes',\n 'encoding': 'base64',\n 'data': base64.b64encode(obj).decode('ascii'),\n }\n\n model_dump = getattr(obj, 'model_dump', None)\n if callable(model_dump):\n try:\n return model_dump(by_alias=True, mode='json')\n except TypeError:\n return model_dump(by_alias=True)\n\n if isinstance(obj, (set, frozenset)):\n return list(obj)\n\n if isinstance(obj, complex):\n raise TypeError(f'Object of type {type(obj).__name__} is not JSON serializable')\n\n raise TypeError(f'Object of type {type(obj).__name__} is not JSON serializable')\n\n return default_encoder\n\n\ndef encode_value(value, *, allow_nan):\n \"\"\"\n JSON-encode a fully-serialized response value, applying the BridgeCodec-equivalent\n default encoder and rejecting NaN/Infinity when allow_nan is False.\n\n Raises CodecError (wrapping the json.dumps ValueError) on NaN/Infinity, matching\n BridgeCodec's \"Cannot serialize NaN...\" wording so error parity holds.\n \"\"\"\n try:\n return json.dumps(value, default=make_default_encoder(allow_nan=allow_nan), allow_nan=allow_nan)\n except ValueError as exc:\n error_msg = str(exc).lower()\n # json.dumps(allow_nan=False) rejects NaN/Infinity with a ValueError whose\n # wording is Python-version dependent: 3.12+ appends the offending value\n # (\"...not JSON compliant: nan\"), but 3.10/3.11 emit only the canonical\n # \"Out of range float values are not JSON compliant\". Match that phrase too\n # so the typed error message is stable across versions.\n nonfinite_token = re.search(r'(^|[^a-z])(nan|inf|infinity)([^a-z]|$)', error_msg)\n if (\n not allow_nan and 'out of range float values are not json compliant' in error_msg\n ) or nonfinite_token:\n raise CodecError('Cannot serialize NaN - NaN/Infinity not allowed in JSON') from exc\n raise CodecError(f'JSON encoding failed: {exc}') from exc\n except TypeError as exc:\n raise CodecError(f'JSON encoding failed: {exc}') from exc\n\n\nclass BridgeCodec:\n \"\"\"Safe JSON codec with explicit value handling and payload-size limits.\"\"\"\n\n def __init__(self, allow_nan=False, max_payload_bytes=10 * 1024 * 1024):\n self.allow_nan = allow_nan\n self.max_payload_bytes = max_payload_bytes\n self._encoder = make_default_encoder(allow_nan=allow_nan)\n\n def encode(self, value):\n result = encode_value(value, allow_nan=self.allow_nan)\n if len(result.encode('utf-8')) > self.max_payload_bytes:\n raise CodecError(f'Payload exceeds {self.max_payload_bytes} bytes')\n return result\n\n def decode(self, payload):\n if len(payload.encode('utf-8')) > self.max_payload_bytes:\n raise CodecError(f'Payload exceeds {self.max_payload_bytes} bytes')\n try:\n return json.loads(payload)\n except json.JSONDecodeError as exc:\n raise CodecError(f'JSON decoding failed: {exc}') from exc\n\n def _default_encoder(self, obj):\n \"\"\"Compatibility hook for callers that used the codec's JSON encoder.\"\"\"\n return self._encoder(obj)\n\n\n_default_codec = None\n\n\ndef get_default_codec():\n \"\"\"Return the lazily-created default BridgeCodec instance.\"\"\"\n global _default_codec\n if _default_codec is None:\n _default_codec = BridgeCodec()\n return _default_codec\n\n\ndef encode(value, *, allow_nan=False):\n \"\"\"Encode a value with the default codec settings.\"\"\"\n if allow_nan:\n return BridgeCodec(allow_nan=True).encode(value)\n return get_default_codec().encode(value)\n\n\ndef decode(payload):\n \"\"\"Decode a JSON payload with the default codec settings.\"\"\"\n return get_default_codec().decode(payload)\n\n\n# =============================================================================\n# REQUEST VALIDATION + HANDLERS + DISPATCH\n# =============================================================================\n\ndef require_protocol(msg):\n if not isinstance(msg, dict):\n raise ProtocolError('Invalid request payload')\n proto = msg.get('protocol')\n if proto != PROTOCOL:\n raise ProtocolError(f'Invalid protocol: {proto}')\n mid = msg.get('id')\n if not isinstance(mid, int):\n raise ProtocolError(f'Invalid request id: {mid}')\n return mid\n\n\ndef require_str(params, key):\n value = params.get(key)\n if not isinstance(value, str) or not value:\n raise ProtocolError(f'Missing {key}')\n return value\n\n\ndef coerce_list(value, key):\n if value is None:\n return []\n if not isinstance(value, list):\n raise ProtocolError(f'Invalid {key}')\n return value\n\n\ndef coerce_dict(value, key):\n if value is None:\n return {}\n if not isinstance(value, dict):\n raise ProtocolError(f'Invalid {key}')\n return value\n\n\ndef handle_call(\n params,\n *,\n force_json_markers,\n torch_allow_copy,\n allowed_modules,\n allow_private_attrs,\n has_envelope_markers,\n):\n module_name = require_str(params, 'module')\n function_name = require_str(params, 'functionName')\n args = deserialize(coerce_list(params.get('args'), 'args'), has_envelope_markers=has_envelope_markers)\n kwargs = deserialize(coerce_dict(params.get('kwargs'), 'kwargs'), has_envelope_markers=has_envelope_markers)\n mod = import_allowed_module(module_name, allowed_modules)\n # function_name may be dotted ('Class.method') for @classmethod/@staticmethod\n # calls, which the generated wrapper routes through call() rather than an\n # instance handle. resolve_allowed_attr_path guards each segment.\n func = resolve_allowed_attr_path(mod, function_name, allow_private_attrs=allow_private_attrs)\n res = func(*args, **kwargs)\n return serialize(res, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy)\n\n\ndef build_meta(\n *,\n bridge,\n pid,\n python_version,\n codec_fallback,\n arrow_available_override=None,\n):\n \"\"\"\n Build the bridge metadata payload.\n\n Field order here is part of the wire contract (the JS validator and the\n documented BridgeInfo shape). Callers supply the backend-specific identity:\n the subprocess server passes bridge='python-subprocess' and a real pid; the\n Pyodide server passes bridge='pyodide' and pid=None.\n\n arrow_available_override: when not None, report this value for arrowAvailable\n instead of probing pyarrow. The Pyodide server forces markers to JSON\n unconditionally, so it advertises arrowAvailable=False regardless of whether\n pyarrow happens to be importable in the WASM environment.\n \"\"\"\n arrow = arrow_available() if arrow_available_override is None else arrow_available_override\n meta = {\n 'protocol': PROTOCOL,\n 'protocolVersion': PROTOCOL_VERSION,\n 'bridge': bridge,\n 'pythonVersion': python_version,\n 'pid': pid,\n 'codecFallback': codec_fallback,\n 'arrowAvailable': arrow,\n 'scipyAvailable': module_available('scipy'),\n 'torchAvailable': module_available('torch'),\n 'sklearnAvailable': module_available('sklearn'),\n 'instances': 0,\n }\n return meta\n\n\ndef dispatch_request(\n msg,\n *,\n bridge,\n pid,\n force_json_markers,\n allow_nan=False,\n python_version=None,\n torch_allow_copy=False,\n arrow_available_override=None,\n allowed_modules=None,\n allow_private_attrs=False,\n has_envelope_markers=True,\n):\n \"\"\"\n Validate and route a request, returning the fully-serialized response dict\n ({'id', 'protocol', 'result'}). Raises ProtocolError for malformed requests\n and propagates handler exceptions to the caller, which is responsible for\n building the error envelope (so it controls traceback inclusion).\n\n allow_nan is accepted for signature symmetry; NaN rejection happens during\n the final encode_value() call, which the caller performs.\n\n allowed_modules: None (default) disables the import allowlist so existing\n behavior is preserved. Supplying a set restricts call imports to\n those modules (plus the stdlib the bridge itself needs) and raises\n ImportNotAllowedError otherwise. allow_private_attrs=False (default) blocks\n getattr of underscore-prefixed names; True restores unrestricted access. See\n the IMPORT / ATTRIBUTE ALLOWLIST section above for the full trust model.\n \"\"\"\n mid = require_protocol(msg)\n method = msg.get('method')\n if not isinstance(method, str):\n raise ProtocolError('Missing method')\n params = coerce_dict(msg.get('params'), 'params')\n if method == 'call':\n result = handle_call(\n params,\n force_json_markers=force_json_markers,\n torch_allow_copy=torch_allow_copy,\n allowed_modules=allowed_modules,\n allow_private_attrs=allow_private_attrs,\n has_envelope_markers=has_envelope_markers,\n )\n elif method == 'meta':\n if python_version is None:\n import sys\n python_version = sys.version.split()[0]\n codec_fallback = 'json' if force_json_markers else 'none'\n result = build_meta(\n bridge=bridge,\n pid=pid,\n python_version=python_version,\n codec_fallback=codec_fallback,\n arrow_available_override=arrow_available_override,\n )\n else:\n raise ProtocolError(f'Unknown method: {method}')\n return {'id': mid, 'protocol': PROTOCOL, 'result': result}\n\n\ndef build_error_payload(mid, exc, *, include_traceback):\n \"\"\"\n Build a protocol error response. Protocol/validation errors omit traceback;\n handler errors include it. Field order matches the reference server.\n \"\"\"\n error = {'type': type(exc).__name__, 'message': str(exc)}\n if include_traceback:\n error['traceback'] = traceback.format_exc()\n return {\n 'id': mid if mid is not None else -1,\n 'protocol': PROTOCOL,\n 'error': error,\n }\n"; +export const PYODIDE_BRIDGE_CORE_SOURCE: string = "\"\"\"\nShared tywrap bridge core: protocol dispatch + value (de)serialization.\n\nThis module is the SINGLE source of truth for the \"tywrap/1\" server-side\nprotocol. It is imported by:\n\n - runtime/python_bridge.py (the Node/Bun/Deno subprocess server and the HTTP\n server), which owns I/O concerns: the stdin/stdout JSONL loop, env-var size\n guards, the real OS pid, bridge='python-subprocess', and the final BridgeCodec\n encode wrapper.\n\n - the in-WASM Pyodide server (src/runtime/pyodide-transport.ts). Pyodide cannot read\n this file from disk, so it is shipped as a build-time-generated TypeScript\n string constant (src/runtime/pyodide-bootstrap-core.generated.ts) produced by\n scripts/generate-pyodide-bootstrap.mjs and exec'd into a module registered in\n sys.modules. A conformance drift guard (test/runtime_conformance.test.ts)\n asserts the generated constant stays byte-identical to this file.\n\nCROSS-LANGUAGE CONTRACT (Python <-> the TypeScript decoder in src/utils/codec.ts\nand the request encoder in src/runtime/bridge-codec.ts):\n\n * Every value-type \"marker\" envelope carries {'__tywrap__': ,\n 'codecVersion': 1, 'encoding': ...}. The 6 markers are: ndarray, dataframe,\n series, scipy.sparse, torch.tensor, sklearn.estimator.\n * bytes round-trip both ways via base64 envelopes (see _deserialize_bytes_*\n and the bytes branch of default_encoder).\n * NaN/Infinity are rejected (the JS client cannot parse the non-standard tokens\n that allow_nan=True would emit).\n\nPURITY: This module depends only on the standard library plus LAZY optional\nimports (numpy/pandas/scipy/torch/sklearn/pyarrow are each imported inside the\nfunction that needs them). It performs no stdin/stdout I/O and reads no env vars,\nso it runs unchanged under CPython-in-WASM (Pyodide).\n\nforce_json_markers: a *parameter* threaded through every serializer (including\nthe nested torch.tensor -> ndarray call). When True, ndarray/dataframe/series are\nforced down their JSON path regardless of pyarrow availability. Pyodide passes\nTrue (Arrow is unavailable in WASM); the subprocess server passes the boolean\nderived from TYWRAP_CODEC_FALLBACK=json so that \"Node in json-fallback mode\" and\n\"Pyodide\" produce byte-identical marker envelopes.\n\"\"\"\n\nimport base64\nimport datetime as dt\nimport decimal\nimport importlib\nimport importlib.util\nimport json\nimport math\nimport re\nimport sys\nimport traceback\nimport uuid\nfrom pathlib import Path, PurePath\n\n# Protocol constants. These MUST match src/runtime/protocol.ts (PROTOCOL_ID,\n# TYWRAP_PROTOCOL_VERSION) and the codec version baked into marker envelopes.\nPROTOCOL = 'tywrap/1'\nPROTOCOL_VERSION = 1\nCODEC_VERSION = 1\nMAX_SERIALIZE_DEPTH = 900\nMAX_SERIALIZE_NODES = 1_000_000\nJS_SAFE_INTEGER_MAX = 2**53 - 1\n_SERIALIZE_PATH_IDENTIFIER = re.compile(r'^[A-Za-z_$][\\w$]*$', re.ASCII)\n\n\nclass ProtocolError(Exception):\n \"\"\"Raised for malformed requests (bad protocol/id/method/params).\"\"\"\n\n\nclass ImportNotAllowedError(PermissionError):\n \"\"\"Raised when a requested module import is not on the active allowlist.\"\"\"\n\n def __init__(self, module_name):\n super().__init__(\n f'Import of module {module_name!r} is not permitted by the tywrap bridge '\n 'allowlist; add it to TYWRAP_ALLOWED_MODULES (subprocess) or the '\n 'allowed_modules parameter to enable it'\n )\n\n\nclass AttributeNotAllowedError(PermissionError):\n \"\"\"Raised when access to a private/dunder attribute is denied by policy.\"\"\"\n\n def __init__(self, attr_name):\n super().__init__(\n f'Access to attribute {attr_name!r} is not permitted by the tywrap bridge: '\n 'underscore-prefixed (private/dunder) attributes are blocked to prevent '\n 'sandbox-escape via attributes like __globals__/__subclasses__/__builtins__; '\n 'set TYWRAP_ALLOW_PRIVATE_ATTRS=1 (subprocess) or pass allow_private_attrs=True '\n 'to override'\n )\n\n\n# =============================================================================\n# IMPORT / ATTRIBUTE ALLOWLIST (trust boundary enforcement)\n# =============================================================================\n#\n# The bridge dispatches call requests by importing the requested module and\n# getattr-ing the requested function/class method. That is an\n# arbitrary import+getattr+call surface, so two complementary guards live here.\n# Both are PURE (no env reads) so the rules behave identically under the\n# subprocess server and the in-WASM Pyodide server; the subprocess server derives\n# the parameters from env vars (TYWRAP_ALLOWED_MODULES / TYWRAP_ALLOW_PRIVATE_ATTRS)\n# and threads them in, exactly like force_json_markers / torch_allow_copy.\n#\n# 1. MODULE ALLOWLIST (opt-in, default = allow all):\n# allowed_modules=None means \"no restriction\" so existing configurations keep\n# working unchanged. When a caller supplies a set, only those modules (plus the\n# stdlib the bridge itself needs to serialize results, see _BRIDGE_REQUIRED_MODULES)\n# may be imported; submodules of an allowed module are permitted (e.g. allowing\n# 'scipy' also allows 'scipy.sparse'). A non-allowlisted import fails LOUDLY with\n# ImportNotAllowedError rather than silently importing.\n#\n# 2. PRIVATE-ATTRIBUTE BLOCK (default ON):\n# getattr of any name starting with '_' (single-underscore private OR dunder) is\n# rejected. This blocks the classic escape chain (obj.__class__.__subclasses__()\n# /__globals__/__builtins__/__import__) without depending on the module allowlist.\n# tywrap-generated wrappers never reference underscore-prefixed names (the IR\n# analyzer skips them), so this does not regress generated code. Set\n# allow_private_attrs=True to restore unrestricted getattr for trusted callers.\n\n# Stdlib modules the bridge's own serialization/handlers may need to import even\n# when a caller-supplied allowlist is active. Optional codec deps (numpy, pandas,\n# scipy, torch, sklearn, pyarrow) are intentionally NOT here: if a caller restricts\n# modules, they must opt those in explicitly. These names cover only what the\n# bridge core itself imports.\n_BRIDGE_REQUIRED_MODULES = frozenset(\n {\n 'base64',\n 'datetime',\n 'decimal',\n 'importlib',\n 'json',\n 'math',\n 'sys',\n 'traceback',\n 'uuid',\n 'pathlib',\n }\n)\n\n\ndef _top_level_package(module_name):\n \"\"\"Return the top-level package of a dotted module name ('a.b.c' -> 'a').\"\"\"\n return module_name.split('.', 1)[0]\n\n\ndef _is_module_allowed(module_name, allowed_modules):\n \"\"\"\n Return True when module_name may be imported under the active policy.\n\n allowed_modules=None disables enforcement (allow all). Otherwise a module is\n allowed when it (or its top-level package) is explicitly listed, or it is one\n of the stdlib modules the bridge itself requires.\n \"\"\"\n if allowed_modules is None:\n return True\n if module_name in allowed_modules or module_name in _BRIDGE_REQUIRED_MODULES:\n return True\n top = _top_level_package(module_name)\n return top in allowed_modules or top in _BRIDGE_REQUIRED_MODULES\n\n\ndef import_allowed_module(module_name, allowed_modules):\n \"\"\"\n Import module_name only if permitted by the allowlist, else raise loudly.\n\n This is the single chokepoint every handler routes module imports through.\n \"\"\"\n if not _is_module_allowed(module_name, allowed_modules):\n raise ImportNotAllowedError(module_name)\n return importlib.import_module(module_name)\n\n\ndef get_allowed_attr(obj, attr_name, *, allow_private_attrs):\n \"\"\"\n getattr(obj, attr_name) with the private/dunder block applied.\n\n Rejects any underscore-prefixed name unless allow_private_attrs is True. This\n is the single chokepoint every handler routes attribute access through.\n \"\"\"\n if not allow_private_attrs and attr_name.startswith('_'):\n raise AttributeNotAllowedError(attr_name)\n return getattr(obj, attr_name)\n\n\ndef resolve_allowed_attr_path(root, dotted_name, *, allow_private_attrs):\n \"\"\"\n Resolve a possibly-dotted attribute path from root, applying the\n private/dunder getattr guard to EVERY segment.\n\n A single segment (the common case, e.g. a module-level function) behaves\n exactly like get_allowed_attr. Dotted names exist because @classmethod and\n @staticmethod are invoked through their owning class: the generated wrapper\n emits call(module, 'Class.method', ...), so the bridge must walk\n module -> Class -> method. Guarding each segment means 'Class._secret' or\n '_Hidden.method' are rejected exactly as a direct private getattr would be —\n the dotted path opens no access the single-getattr path did not already.\n \"\"\"\n obj = root\n for segment in dotted_name.split('.'):\n obj = get_allowed_attr(obj, segment, allow_private_attrs=allow_private_attrs)\n return obj\n\n\nclass CodecError(Exception):\n \"\"\"Raised when value encoding fails (e.g. NaN/Infinity not allowed).\"\"\"\n\n\n# =============================================================================\n# REQUEST-SIDE DESERIALIZATION (bytes envelopes -> Python bytes)\n# =============================================================================\n\n_NO_DESERIALIZE = object()\n_ERR_BYTES_MISSING_B64 = 'Invalid bytes envelope: missing b64'\n_ERR_BYTES_MISSING_DATA = 'Invalid bytes envelope: missing data'\n_ERR_BYTES_INVALID_BASE64 = 'Invalid bytes envelope: invalid base64'\n\n\ndef _deserialize_bytes_envelope(value):\n \"\"\"\n Decode base64-encoded bytes envelopes from JS into Python bytes.\n\n Supported shapes:\n - { \"__tywrap_bytes__\": true, \"b64\": \"...\" } (JS BridgeCodec.encodeRequest)\n - { \"__type__\": \"bytes\", \"encoding\": \"base64\", \"data\": \"...\" } (legacy/compat)\n\n Why: TS BridgeCodec encodes Uint8Array/ArrayBuffer as base64 objects, but\n Python handlers expect real bytes/bytearray to preserve behavior (e.g., len()).\n \"\"\"\n if not isinstance(value, dict):\n return _NO_DESERIALIZE\n\n if value.get('__tywrap_bytes__') is True:\n b64 = value.get('b64')\n if not isinstance(b64, str):\n raise ProtocolError(_ERR_BYTES_MISSING_B64)\n try:\n return base64.b64decode(b64, validate=True)\n except Exception as exc:\n raise ProtocolError(_ERR_BYTES_INVALID_BASE64) from exc\n\n if value.get('__type__') == 'bytes' and value.get('encoding') == 'base64':\n data = value.get('data')\n if not isinstance(data, str):\n raise ProtocolError(_ERR_BYTES_MISSING_DATA)\n try:\n return base64.b64decode(data, validate=True)\n except Exception as exc:\n raise ProtocolError(_ERR_BYTES_INVALID_BASE64) from exc\n\n return _NO_DESERIALIZE\n\n\ndef deserialize(value, *, has_envelope_markers=True):\n \"\"\"\n Recursively deserialize request values into Python-native types.\n\n Why: requests are JSON-only; we need a small set of explicit decoders\n (currently bytes) to restore Python semantics at the boundary.\n \"\"\"\n if not has_envelope_markers:\n return value\n decoded = _deserialize_bytes_envelope(value)\n if decoded is not _NO_DESERIALIZE:\n return decoded\n\n if isinstance(value, list):\n return [deserialize(item, has_envelope_markers=True) for item in value]\n if isinstance(value, dict):\n # Preserve dict shape while decoding nested values.\n return {k: deserialize(v, has_envelope_markers=True) for k, v in value.items()}\n return value\n\n\n# =============================================================================\n# CAPABILITY DETECTION (lazy, best-effort)\n# =============================================================================\n\ndef arrow_available():\n \"\"\"Return True when pyarrow can be imported.\"\"\"\n try:\n import pyarrow # noqa: F401\n except (ImportError, OSError):\n return False\n return True\n\n\ndef module_available(module_name):\n \"\"\"\n Lightweight feature detection for optional codec dependencies via find_spec.\n\n Why: exposes availability in bridge metadata without importing heavy modules.\n \"\"\"\n try:\n return importlib.util.find_spec(module_name) is not None\n except (ImportError, AttributeError, TypeError, ValueError):\n return False\n\n\ndef is_numpy_array(obj):\n \"\"\"Return whether obj is an ndarray without importing NumPy.\"\"\"\n np = sys.modules.get('numpy')\n if np is None:\n return False\n return isinstance(obj, np.ndarray)\n\n\ndef is_pandas_dataframe(obj):\n \"\"\"Return whether obj is a DataFrame without importing pandas.\"\"\"\n pd = sys.modules.get('pandas')\n if pd is None:\n return False\n return isinstance(obj, pd.DataFrame)\n\n\ndef is_pandas_series(obj):\n \"\"\"Return whether obj is a Series without importing pandas.\"\"\"\n pd = sys.modules.get('pandas')\n if pd is None:\n return False\n return isinstance(obj, pd.Series)\n\n\ndef is_scipy_sparse(obj):\n \"\"\"Return whether obj is sparse without importing SciPy.\"\"\"\n sp = sys.modules.get('scipy.sparse')\n if sp is None:\n return False\n try:\n return sp.issparse(obj)\n except Exception:\n return False\n\n\ndef is_torch_tensor(obj):\n \"\"\"Return whether obj is a Tensor without importing PyTorch.\"\"\"\n torch = sys.modules.get('torch')\n if torch is None:\n return False\n try:\n return torch.is_tensor(obj)\n except Exception:\n return False\n\n\ndef is_sklearn_estimator(obj):\n \"\"\"Return whether obj is an estimator without importing scikit-learn.\"\"\"\n sklearn_base = sys.modules.get('sklearn.base')\n if sklearn_base is None:\n return False\n return isinstance(obj, sklearn_base.BaseEstimator)\n\n\n# =============================================================================\n# MARKER SERIALIZERS (6 __tywrap__ value types)\n# =============================================================================\n#\n# Each serializer accepts force_json_markers. When True, the Arrow path is never\n# taken (used by Pyodide and by the subprocess server in TYWRAP_CODEC_FALLBACK=json\n# mode). The JSON fallback envelopes are byte-identical across both callers, which\n# is what the conformance suite asserts.\n\ndef serialize_ndarray(obj, *, force_json_markers):\n \"\"\"\n Encode a NumPy ndarray. Arrow IPC (compact, lossless) by default; JSON when\n force_json_markers is set or pyarrow is unavailable in fallback mode.\n\n Note: pa.array() only handles 1D arrays; multi-dimensional arrays are\n flattened with shape metadata for JS-side reconstruction. See\n https://github.com/apache/arrow-js/issues/115\n \"\"\"\n if force_json_markers:\n return serialize_ndarray_json(obj)\n try:\n import pyarrow as pa # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for ndarray; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n original_shape = list(obj.shape) if hasattr(obj, 'shape') else None\n flat = obj.flatten() if hasattr(obj, 'ndim') and obj.ndim != 1 else obj\n arr = pa.array(flat)\n table = pa.Table.from_arrays([arr], names=['value'])\n sink = pa.BufferOutputStream()\n with pa.ipc.new_stream(sink, table.schema) as writer:\n writer.write_table(table)\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'ndarray',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n 'shape': original_shape,\n 'dtype': str(obj.dtype) if hasattr(obj, 'dtype') else None,\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for ndarray') from exc\n\n\ndef serialize_ndarray_json(obj):\n \"\"\"JSON fallback for ndarray values that JavaScript can represent safely.\"\"\"\n dtype = obj.dtype\n dtype_label = str(dtype)\n\n if not dtype.isnative:\n raise RuntimeError(\n f'JSON ndarray encoding does not support big-endian dtype={dtype_label}; '\n \"convert to native byte order with a.byteswap().view(a.dtype.newbyteorder('='))\"\n )\n\n if dtype.kind in ('i', 'u'):\n # JSON numbers become JavaScript Number values. Scan only on this explicit\n # fallback path and reject before tolist() can silently round an integer.\n if obj.size and (\n (obj < -JS_SAFE_INTEGER_MAX).any() or (obj > JS_SAFE_INTEGER_MAX).any()\n ):\n raise RuntimeError(\n f'JSON ndarray encoding cannot safely represent dtype={dtype_label} values '\n 'outside the JavaScript safe integer range; use Arrow encoding or '\n \"cast/encode explicitly (e.g. .astype('float64') or str)\"\n )\n elif dtype.kind == 'M':\n raise RuntimeError(\n f'JSON ndarray encoding does not support dtype={dtype_label}; use Arrow encoding '\n \"or convert explicitly (e.g. .astype('datetime64[ms]').astype(str) or int with \"\n 'declared unit)'\n )\n elif dtype.kind == 'm':\n raise RuntimeError(\n f'JSON ndarray encoding does not support dtype={dtype_label}; use Arrow encoding '\n \"or convert explicitly (e.g. .astype('timedelta64[ms]').astype(str) or int with \"\n 'declared unit)'\n )\n elif dtype.kind == 'V':\n if dtype.fields is not None:\n raise RuntimeError(\n f'JSON ndarray encoding does not support structured dtype={dtype_label}; '\n 'encode each named field explicitly (e.g. as a plain JSON object)'\n )\n raise RuntimeError(\n f'JSON ndarray encoding does not support void dtype={dtype_label}; convert the '\n \"raw bytes explicitly (e.g. .view('uint8'))\"\n )\n elif dtype.kind == 'O':\n raise RuntimeError(\n f'JSON ndarray encoding does not support object dtype={dtype_label}; cast to a '\n 'concrete numeric dtype or encode elements explicitly as plain JSON'\n )\n elif dtype.kind == 'S':\n raise RuntimeError(\n f'JSON ndarray encoding does not support byte-string dtype={dtype_label}; '\n 'decode elements and return a plain JSON list explicitly'\n )\n elif dtype.kind == 'U':\n raise RuntimeError(\n f'JSON ndarray encoding does not support unicode dtype={dtype_label}; convert '\n 'explicitly to plain JSON strings with .tolist()'\n )\n elif dtype.kind == 'c':\n raise RuntimeError(\n f'JSON ndarray encoding does not support complex dtype={dtype_label}; encode '\n '.real and .imag arrays explicitly'\n )\n elif dtype.kind == 'f' and dtype.itemsize > 8:\n raise RuntimeError(\n f'JSON ndarray encoding does not support float dtype={dtype_label} wider than '\n \"64 bits; cast explicitly (e.g. .astype('float64')) or use Arrow encoding\"\n )\n elif dtype.kind not in ('b', 'f'):\n raise RuntimeError(\n f'JSON ndarray encoding does not support dtype={dtype_label}; cast to bool, '\n 'integer, or float dtype, or encode values explicitly as plain JSON'\n )\n\n try:\n data = obj.tolist()\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for ndarray') from exc\n return {\n '__tywrap__': 'ndarray',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n 'shape': getattr(obj, 'shape', None),\n 'dtype': dtype.name,\n }\n\n\ndef serialize_dataframe(obj, *, force_json_markers):\n \"\"\"\n Encode a pandas DataFrame. Feather/Arrow-IPC (uncompressed, so apache-arrow\n in JS can read it) by default; JSON when force_json_markers is set.\n \"\"\"\n if force_json_markers:\n return serialize_dataframe_json(obj)\n try:\n import pyarrow as pa # type: ignore\n import pyarrow.feather as feather # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for pandas.DataFrame; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n table = pa.Table.from_pandas(obj) # type: ignore\n sink = pa.BufferOutputStream()\n feather.write_feather(table, sink, compression='uncompressed')\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'dataframe',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for pandas.DataFrame') from exc\n\n\ndef serialize_dataframe_json(obj):\n \"\"\"JSON fallback for DataFrame values that JavaScript can represent safely.\"\"\"\n import pandas as pd # type: ignore\n\n _validate_pandas_json_index(obj.index, pd, 'DataFrame')\n json_columns = [_json_object_key(column) for column in obj.columns]\n supported_json_columns = [column for column in json_columns if column is not None]\n if not obj.columns.is_unique or len(set(supported_json_columns)) != len(\n supported_json_columns\n ):\n raise RuntimeError(\n 'JSON pandas.DataFrame encoding requires column labels to remain unique after '\n 'JSON object-key coercion; rename columns or make them distinct before applying '\n '.columns.astype(str)'\n )\n for column, dtype in obj.dtypes.items():\n if isinstance(dtype, pd.CategoricalDtype):\n raise RuntimeError(\n f'JSON pandas.DataFrame encoding does not support categorical dtype in '\n f'column {column!r}; use Arrow encoding or convert explicitly '\n \"(e.g. .astype(str))\"\n )\n try:\n data = (\n [{} for _ in range(len(obj.index))]\n if len(obj.columns) == 0\n else obj.to_dict(orient='records')\n )\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for pandas.DataFrame') from exc\n for row_number, row in enumerate(data):\n for column, value in row.items():\n row[column] = _normalize_pandas_json_scalar(\n value,\n f'DataFrame cell at row {row_number}, column {column!r}',\n pd,\n )\n return {\n '__tywrap__': 'dataframe',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n }\n\n\ndef serialize_series(obj, *, force_json_markers, path='result'):\n \"\"\"\n Encode a pandas Series as a single-column Arrow Table stream (the JS decoder\n contract is \"table-like\"); JSON when force_json_markers is set.\n \"\"\"\n if force_json_markers:\n return serialize_series_json(obj, path=path)\n name = getattr(obj, 'name', None)\n _check_terminal_json_integers(\n encode_value(name, allow_nan=False), _serialize_path(path, 'name')\n )\n try:\n import pyarrow as pa # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for pandas.Series; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n arr = pa.Array.from_pandas(obj) # type: ignore\n table = pa.Table.from_arrays([arr], names=['value'])\n sink = pa.BufferOutputStream()\n with pa.ipc.new_stream(sink, table.schema) as writer:\n writer.write_table(table)\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'series',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n 'name': name,\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for pandas.Series') from exc\n\n\ndef serialize_series_json(obj, *, path='result'):\n \"\"\"JSON fallback for Series values that JavaScript can represent safely.\"\"\"\n import pandas as pd # type: ignore\n\n _validate_pandas_json_index(obj.index, pd, 'Series')\n if isinstance(obj.dtype, pd.CategoricalDtype):\n raise RuntimeError(\n 'JSON pandas.Series encoding does not support categorical dtype; use Arrow '\n \"encoding or convert explicitly (e.g. .astype(str))\"\n )\n try:\n data = obj.to_list() # type: ignore\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for pandas.Series') from exc\n data = [\n _normalize_pandas_json_scalar(value, f'Series value at position {position}', pd)\n for position, value in enumerate(data)\n ]\n name = getattr(obj, 'name', None)\n _check_terminal_json_integers(\n encode_value(name, allow_nan=False), _serialize_path(path, 'name')\n )\n return {\n '__tywrap__': 'series',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n 'name': name,\n }\n\n\ndef _validate_pandas_json_index(index, pd, container_name):\n \"\"\"Reject index metadata that records/list-oriented JSON would discard.\"\"\"\n if isinstance(index, pd.MultiIndex):\n raise RuntimeError(\n f'JSON pandas.{container_name} encoding does not support MultiIndex; use Arrow '\n 'encoding or flatten the index explicitly with .reset_index()'\n )\n if not (\n isinstance(index, pd.RangeIndex)\n and index.start == 0\n and index.step == 1\n and index.stop == len(index)\n and index.name is None\n ):\n raise RuntimeError(\n f'JSON pandas.{container_name} encoding requires an unnamed RangeIndex starting '\n 'at 0 with step 1; use Arrow encoding or normalize explicitly with '\n '.reset_index(drop=True)'\n )\n\n\ndef _json_object_key(value):\n \"\"\"Return json.dumps' object-key spelling, or None for unsupported keys.\"\"\"\n try:\n encoded = json.dumps({value: None})\n except (TypeError, ValueError):\n return None\n return next(iter(json.loads(encoded)))\n\n\ndef _normalize_pandas_json_scalar(value, location, pd):\n \"\"\"Normalize pandas nulls and reject values outside the plain JSON domain.\"\"\"\n np = sys.modules.get('numpy')\n if np is not None and isinstance(value, np.generic):\n value = value.item()\n if value is None or value is pd.NA or value is pd.NaT:\n return None\n if type(value) is bool:\n return value\n if type(value) is int:\n if value < -JS_SAFE_INTEGER_MAX or value > JS_SAFE_INTEGER_MAX:\n raise RuntimeError(\n f'JSON pandas encoding cannot safely represent {location} integer values '\n 'outside the JavaScript safe integer range; use Arrow encoding or '\n \"cast/encode explicitly (e.g. .astype('float64') or str)\"\n )\n return value\n if type(value) is float:\n if not math.isfinite(value):\n raise RuntimeError(\n f'JSON pandas encoding cannot represent non-finite {location} float values '\n '(NaN or Infinity); use .fillna(...) for intentional missing values or '\n 'Arrow encoding'\n )\n return value\n if type(value) is str:\n return value\n raise RuntimeError(\n f'JSON pandas encoding does not support {location} value of type '\n f'{type(value).__name__}; use Arrow encoding or convert explicitly '\n '(e.g. .astype(str))'\n )\n\n\ndef serialize_sparse_matrix(obj, *, path='result'):\n \"\"\"\n Serialize scipy sparse matrices into structured JSON envelopes (json-only;\n there is no Arrow path). Preserves sparsity; rejects unsupported formats and\n complex dtypes explicitly.\n \"\"\"\n try:\n fmt = obj.getformat()\n except Exception as exc:\n raise RuntimeError('Failed to inspect scipy sparse matrix format') from exc\n\n if fmt not in ('csr', 'csc', 'coo'):\n raise RuntimeError(\n f'Unsupported scipy sparse format: {fmt}; only csr/csc/coo are supported. '\n 'Convert explicitly (e.g. matrix.tocsr()) before returning'\n )\n\n dtype = None\n try:\n dtype = str(obj.dtype)\n except Exception:\n dtype = None\n if getattr(obj.dtype, 'kind', None) == 'c':\n raise RuntimeError(\n 'Complex scipy sparse matrices are not supported by the JSON codec; '\n 'split into real/imag components explicitly before returning'\n )\n if getattr(obj.dtype, 'kind', None) in ('i', 'u') and obj.data.size and (\n (obj.data < -JS_SAFE_INTEGER_MAX).any()\n or (obj.data > JS_SAFE_INTEGER_MAX).any()\n ):\n raise RuntimeError(\n 'JSON scipy sparse encoding cannot safely represent data outside the '\n 'JavaScript safe integer range; cast or encode the values explicitly'\n )\n\n for index, dimension in enumerate(obj.shape):\n if int.__int__(dimension) > JS_SAFE_INTEGER_MAX:\n raise RuntimeError(\n f'Unsafe Python integer at {_serialize_path(_serialize_path(path, \"shape\"), index)}: '\n f'{dimension} is outside the JavaScript safe integer range'\n )\n index_fields = ('indices', 'indptr') if fmt in ('csr', 'csc') else ('row', 'col')\n for field in index_fields:\n values = getattr(obj, field)\n if values.size and (\n (values < -JS_SAFE_INTEGER_MAX).any()\n or (values > JS_SAFE_INTEGER_MAX).any()\n ):\n raise RuntimeError(\n f'JSON scipy sparse encoding cannot safely represent {field} at '\n f'{_serialize_path(path, field)} outside the JavaScript safe integer range'\n )\n\n if fmt in ('csr', 'csc'):\n data = obj.data.tolist()\n indices = obj.indices.tolist()\n indptr = obj.indptr.tolist()\n return {\n '__tywrap__': 'scipy.sparse',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'format': fmt,\n 'shape': list(obj.shape),\n 'data': data,\n 'indices': indices,\n 'indptr': indptr,\n 'dtype': dtype,\n }\n\n # coo\n data = obj.data.tolist()\n row = obj.row.tolist()\n col = obj.col.tolist()\n return {\n '__tywrap__': 'scipy.sparse',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'format': fmt,\n 'shape': list(obj.shape),\n 'data': data,\n 'row': row,\n 'col': col,\n 'dtype': dtype,\n }\n\n\ndef serialize_torch_tensor(obj, *, force_json_markers, torch_allow_copy=False):\n \"\"\"\n Serialize torch.Tensor values via the nested ndarray envelope. CPU-only by\n default; device/copy behavior is explicit. force_json_markers is threaded\n into the nested ndarray serialization so Pyodide gets a JSON ndarray value.\n\n Rejection order is significant: the categorical rejections (sparse / quantized\n / meta / complex) are checked BEFORE the device/contiguous opt-in branch so\n they fail with a clear, specific message and are NOT bypassable by\n TYWRAP_TORCH_ALLOW_COPY. The opt-in only governs the device transfer and\n contiguous copy, never an unrepresentable layout/dtype.\n \"\"\"\n import torch # already importable: is_torch_tensor() gated the dispatch\n\n tensor = obj.detach()\n source_device = None\n source_dtype = None\n\n # Sparse tensors (COO/CSR/CSC/BSR/BSC -> any non-strided layout) have no dense\n # numpy representation without a densify step, which is not the round-trip this\n # envelope promises. Reject explicitly rather than emitting a misleading\n # \"not contiguous\" error or silently densifying.\n layout = getattr(tensor, 'layout', None)\n if getattr(tensor, 'is_sparse', False) or (\n layout is not None and layout != torch.strided\n ):\n raise RuntimeError(\n f'Torch sparse tensors are not supported (layout={layout}); '\n 'convert to a dense CPU tensor explicitly (e.g. tensor.to_dense()) before returning'\n )\n\n # Quantized tensors carry a qscheme/scale/zero_point that numpy() cannot\n # represent; .numpy() raises an opaque \"unsupported ScalarType\" deep in torch.\n # Reject up front with an actionable message.\n if getattr(tensor, 'is_quantized', False):\n raise RuntimeError(\n 'Torch quantized tensors are not supported; dequantize explicitly '\n '(e.g. tensor.dequantize()) before returning'\n )\n\n # Meta tensors have shape/dtype but NO storage; copying to CPU yields garbage,\n # so this is never a lossy-but-honest transfer the opt-in could authorize.\n if getattr(tensor, 'is_meta', False) or (\n getattr(tensor, 'device', None) is not None and tensor.device.type == 'meta'\n ):\n raise RuntimeError(\n 'Torch meta tensors carry no data and cannot be serialized; '\n 'materialize the tensor on a real device before returning'\n )\n\n # Complex tensors round-trip to numpy complex arrays, which are not\n # JSON-serializable and have no codec envelope. Reject explicitly instead of\n # emitting Python complex tuples that the JS decoder cannot parse.\n if torch.is_complex(tensor):\n raise RuntimeError(\n f'Torch complex tensors are not supported (dtype={tensor.dtype}); '\n 'split into real/imag components explicitly before returning'\n )\n\n if getattr(tensor, 'device', None) is not None and tensor.device.type != 'cpu':\n if not torch_allow_copy:\n raise RuntimeError(\n 'Torch tensor is on a non-CPU device; set TYWRAP_TORCH_ALLOW_COPY=1 to allow CPU transfer'\n )\n source_device = str(tensor.device)\n tensor = tensor.to('cpu')\n if hasattr(tensor, 'is_contiguous') and not tensor.is_contiguous():\n if not torch_allow_copy:\n raise RuntimeError(\n 'Torch tensor is not contiguous; set TYWRAP_TORCH_ALLOW_COPY=1 to allow contiguous copy'\n )\n tensor = tensor.contiguous()\n if tensor.dtype == torch.bfloat16:\n source_dtype = str(tensor.dtype)\n tensor = tensor.float()\n try:\n arr = tensor.numpy()\n except Exception as exc:\n raise RuntimeError('Failed to convert torch.Tensor to numpy') from exc\n\n envelope = {\n '__tywrap__': 'torch.tensor',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'ndarray',\n 'value': serialize_ndarray(arr, force_json_markers=force_json_markers),\n 'shape': list(tensor.shape),\n 'dtype': str(tensor.dtype),\n 'device': str(tensor.device),\n }\n if source_dtype is not None:\n envelope['sourceDtype'] = source_dtype\n if source_device is not None:\n envelope['sourceDevice'] = source_device\n return envelope\n\n\ndef serialize_sklearn_estimator(obj, *, path):\n \"\"\"Serialize sklearn estimators as metadata only (json-only); no pickling.\"\"\"\n try:\n import sklearn # noqa: F401\n except Exception as exc:\n raise RuntimeError('scikit-learn is not available') from exc\n\n params = obj.get_params(deep=False)\n\n # Metadata-only: NEVER pickle/joblib. Every param value must be plain JSON\n # (no callables, nested estimators, numpy arrays, or other objects). Probe\n # each value individually so the error names the offending param instead of\n # failing opaquely on the whole dict. allow_nan=False also rejects NaN/Inf\n # params here for parity with the response codec.\n for key, value in params.items():\n try:\n encoded = json.dumps(value, allow_nan=False)\n param_path = _serialize_path(_serialize_path(path, 'params'), str(key))\n _check_terminal_json_integers(encoded, param_path)\n except RuntimeError:\n raise\n except (TypeError, ValueError) as exc:\n raise RuntimeError(\n f'scikit-learn estimator param {key!r} is not JSON-serializable '\n f'(got {type(value).__name__}); estimators are serialized as metadata only '\n '(no pickle/joblib), so every param must be a plain JSON value. '\n 'Sanitize or drop the param before returning'\n ) from exc\n\n return {\n '__tywrap__': 'sklearn.estimator',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'className': obj.__class__.__name__,\n 'module': obj.__class__.__module__,\n 'version': getattr(sklearn, '__version__', None),\n 'params': params,\n }\n\n\ndef _check_terminal_json_integers(encoded, path):\n \"\"\"Check integer tokens in a small JSON metadata value before emission.\"\"\"\n stack = [(json.loads(encoded), path)]\n while stack:\n current, current_path = stack.pop()\n if type(current) is int:\n _serialize_leaf(current, current_path)\n elif isinstance(current, dict):\n stack.extend(\n (item, _serialize_path(current_path, key))\n for key, item in current.items()\n )\n elif isinstance(current, list):\n stack.extend(\n (item, _serialize_path(current_path, index))\n for index, item in enumerate(current)\n )\n\n\n_NO_PYDANTIC = object()\n\n\ndef serialize_pydantic(obj):\n \"\"\"\n Serialize Pydantic v2 models via model_dump(by_alias=True, mode='json')\n without importing Pydantic. Returns _NO_PYDANTIC when obj is not a model.\n \"\"\"\n model_dump = getattr(obj, 'model_dump', None)\n if not callable(model_dump):\n return _NO_PYDANTIC\n try:\n try:\n return model_dump(by_alias=True, mode='json')\n except TypeError:\n # Older Pydantic versions may not support `mode=...`.\n return model_dump(by_alias=True)\n except Exception as exc:\n raise RuntimeError(f'model_dump failed: {exc}') from exc\n\n\ndef serialize_stdlib(obj):\n \"\"\"Coerce common stdlib scalar types to JSON-safe forms; None otherwise.\"\"\"\n if isinstance(obj, dt.datetime):\n return obj.isoformat()\n if isinstance(obj, dt.date):\n return obj.isoformat()\n if isinstance(obj, dt.time):\n return obj.isoformat()\n if isinstance(obj, dt.timedelta):\n return obj.total_seconds()\n if isinstance(obj, decimal.Decimal):\n return str(obj)\n if isinstance(obj, uuid.UUID):\n return str(obj)\n if isinstance(obj, (Path, PurePath)):\n return str(obj)\n return None\n\n\n_NO_SCIENTIFIC = object()\n\n\ndef _check_serialize_depth(depth, path):\n if depth > MAX_SERIALIZE_DEPTH:\n raise RuntimeError(\n f'Scientific envelope serialization maximum depth '\n f'{MAX_SERIALIZE_DEPTH} exceeded at {path}'\n )\n\n\ndef _check_serialize_nodes(nodes, path):\n if nodes > MAX_SERIALIZE_NODES:\n raise RuntimeError(\n f'Scientific envelope serialization maximum visited nodes '\n f'{MAX_SERIALIZE_NODES} exceeded at {path}'\n )\n\n\ndef _serialize_scientific(obj, *, force_json_markers, torch_allow_copy, depth, path):\n \"\"\"Serialize a supported scientific value, or return _NO_SCIENTIFIC.\"\"\"\n package = type(obj).__module__.split('.', 1)[0]\n\n if package == 'numpy' and 'numpy' in sys.modules:\n if is_numpy_array(obj):\n _check_serialize_depth(depth, path)\n return serialize_ndarray(obj, force_json_markers=force_json_markers)\n elif package == 'pandas' and 'pandas' in sys.modules:\n if is_pandas_dataframe(obj):\n _check_serialize_depth(depth, path)\n return serialize_dataframe(obj, force_json_markers=force_json_markers)\n if is_pandas_series(obj):\n _check_serialize_depth(depth, path)\n return serialize_series(obj, force_json_markers=force_json_markers, path=path)\n elif package == 'scipy' and 'scipy.sparse' in sys.modules:\n if is_scipy_sparse(obj):\n _check_serialize_depth(depth, path)\n return serialize_sparse_matrix(obj, path=path)\n elif package == 'torch' and 'torch' in sys.modules:\n if is_torch_tensor(obj):\n _check_serialize_depth(depth, path)\n _check_serialize_depth(depth + 1, _serialize_path(path, 'value'))\n return serialize_torch_tensor(\n obj, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy\n )\n elif 'sklearn.base' in sys.modules and is_sklearn_estimator(obj):\n # No package gate here, unlike the branches above: subclassing\n # BaseEstimator is sklearn's documented extension point, so user-defined\n # estimators live outside the 'sklearn' package and must still get the\n # estimator serializer (and its param-naming errors).\n _check_serialize_depth(depth, path)\n return serialize_sklearn_estimator(obj, path=path)\n\n return _NO_SCIENTIFIC\n\n\ndef _serialize_path(base, key):\n \"\"\"Build a decoder-compatible JSONPath-like result path.\"\"\"\n if isinstance(key, int):\n return f'{base}[{key}]'\n if _SERIALIZE_PATH_IDENTIFIER.fullmatch(key):\n return f'{base}.{key}'\n return f'{base}[{json.dumps(key, ensure_ascii=False)}]'\n\n\ndef _invalid_key_path(base, key):\n \"\"\"Name a dict key that cannot be represented by JSON.\"\"\"\n return f'{base}[{key!r}]'\n\n\ndef _needs_serialize_visit(value):\n \"\"\"Return whether value needs container or scientific traversal work.\"\"\"\n if type(value) in (type(None), bool, int, float, str):\n return False\n if isinstance(value, (dict, list, tuple, set, frozenset)):\n return True\n package = type(value).__module__.split('.', 1)[0]\n if package in ('numpy', 'pandas', 'scipy', 'torch'):\n return True\n return callable(getattr(value, 'model_dump', None)) or (\n 'sklearn.base' in sys.modules and is_sklearn_estimator(value)\n )\n\n\ndef _serialize_leaf(value, path):\n \"\"\"Apply non-container conversions without allocating a traversal frame.\"\"\"\n integer_value = int.__int__(value) if isinstance(value, int) and not isinstance(value, bool) else None\n if integer_value is not None and (\n integer_value < -JS_SAFE_INTEGER_MAX or integer_value > JS_SAFE_INTEGER_MAX\n ):\n raise RuntimeError(\n f'Unsafe Python integer at {path}: {integer_value} is outside the JavaScript safe '\n 'integer range; return an explicit string or use an Arrow integer column'\n )\n if type(value) in (type(None), bool, int, float, str):\n return value\n np = sys.modules.get('numpy')\n if np is not None and isinstance(value, np.generic):\n extracted = value.item()\n if isinstance(extracted, np.generic):\n raise TypeError(\n f'NumPy scalar at {path} did not convert to a JSON value; '\n 'cast it explicitly before returning'\n )\n return _serialize_leaf(extracted, path)\n pydantic_value = serialize_pydantic(value)\n if pydantic_value is not _NO_PYDANTIC:\n return pydantic_value\n if isinstance(value, (set, frozenset)):\n return list(value)\n stdlib_value = serialize_stdlib(value)\n if stdlib_value is not None:\n return stdlib_value\n return value\n\n\ndef serialize(obj, *, force_json_markers, torch_allow_copy=False):\n \"\"\"\n Top-level result serializer.\n\n Scientific codecs are type-first and only inspect packages that the value can\n belong to. A value from an optional package implies that package is already in\n sys.modules, so these checks never cold-import the scientific stack. The\n package dispatch deliberately precedes the JSON-native fast path: e.g. a\n package-defined subclass of dict still receives its relevant codec check.\n Every other value is left untouched so the shared JSON encoder applies the\n exact same default conversion at the root and at any nested depth.\n \"\"\"\n root = [None]\n active_ids = set()\n stack = [('visit', obj, 0, 'result', root, 0)]\n visited_nodes = 0\n\n # Repeated aliases have value semantics and are intentionally serialized twice.\n while stack:\n frame = stack.pop()\n action = frame[0]\n if action == 'release-model':\n active_ids.remove(frame[1])\n continue\n if action == 'dict':\n _, current, depth, path, parent, key, output, iterator = frame\n try:\n item_key, item = next(iterator)\n except StopIteration:\n active_ids.remove(id(current))\n parent[key] = output\n continue\n stack.append(frame)\n if not (isinstance(item_key, (str, int, float, bool)) or item_key is None):\n invalid_path = _invalid_key_path(path, item_key)\n raise TypeError(\n f'keys must be str, int, float, bool or None, not '\n f'{type(item_key).__name__} at {invalid_path}'\n )\n child_key = _json_object_key(item_key)\n child_path = _serialize_path(path, child_key)\n if _needs_serialize_visit(item):\n stack.append(('visit', item, depth + 1, child_path, output, item_key))\n else:\n output[item_key] = _serialize_leaf(item, child_path)\n continue\n if action == 'sequence':\n _, current, depth, path, parent, key, output, index = frame\n if index == len(output):\n active_ids.remove(id(current))\n parent[key] = output if isinstance(current, list) else tuple(output)\n continue\n stack.append(('sequence', current, depth, path, parent, key, output, index + 1))\n item = current[index]\n child_path = _serialize_path(path, index)\n if _needs_serialize_visit(item):\n stack.append(\n ('visit', item, depth + 1, child_path, output, index)\n )\n else:\n output[index] = _serialize_leaf(item, child_path)\n continue\n\n _, current, depth, path, parent, key = frame\n try:\n scientific = _serialize_scientific(\n current,\n force_json_markers=force_json_markers,\n torch_allow_copy=torch_allow_copy,\n depth=depth,\n path=path,\n )\n except Exception as exc:\n if path == 'result' and 'safe integer range' not in str(exc):\n raise\n raise RuntimeError(f'Scientific value serialization failed at {path}: {exc}') from exc\n if scientific is not _NO_SCIENTIFIC:\n # Recognized envelopes are terminal containers to the JS decoder.\n visited_nodes += 1\n _check_serialize_nodes(visited_nodes, path)\n if scientific.get('__tywrap__') == 'torch.tensor':\n nested_path = _serialize_path(path, 'value')\n try:\n visited_nodes += 1\n _check_serialize_nodes(visited_nodes, nested_path)\n except Exception as exc:\n if path == 'result':\n raise\n raise RuntimeError(\n f'Scientific value serialization failed at {path}: {exc}'\n ) from exc\n parent[key] = scientific\n continue\n\n if callable(getattr(current, 'model_dump', None)):\n _check_serialize_depth(depth, path)\n visited_nodes += 1\n _check_serialize_nodes(visited_nodes, path)\n current_id = id(current)\n if current_id in active_ids:\n raise RuntimeError(f'Circular model conversion detected at {path}')\n active_ids.add(current_id)\n normalized = _serialize_leaf(current, path)\n if normalized is current:\n raise RuntimeError(f'Circular model conversion detected at {path}')\n stack.append(('release-model', current_id))\n if _needs_serialize_visit(normalized):\n stack.append(('visit', normalized, depth + 1, path, parent, key))\n else:\n parent[key] = _serialize_leaf(normalized, path)\n continue\n\n if isinstance(current, (dict, list, tuple)):\n _check_serialize_depth(depth, path)\n visited_nodes += 1\n _check_serialize_nodes(visited_nodes, path)\n current_id = id(current)\n if current_id in active_ids:\n raise RuntimeError(f'Circular reference detected at {path}')\n active_ids.add(current_id)\n\n if isinstance(current, dict):\n output = {}\n parent[key] = output\n stack.append(\n ('dict', current, depth, path, parent, key, output, iter(current.items()))\n )\n continue\n\n output = [None] * len(current)\n if isinstance(current, list):\n parent[key] = output\n stack.append(('sequence', current, depth, path, parent, key, output, 0))\n continue\n\n normalized = _serialize_leaf(current, path)\n if normalized is not current and _needs_serialize_visit(normalized):\n stack.append(('visit', normalized, depth, path, parent, key))\n elif normalized is not current:\n parent[key] = _serialize_leaf(normalized, path)\n else:\n parent[key] = normalized\n\n return root[0]\n\n\n# =============================================================================\n# JSON CODEC: value handling and size-limited encode/decode\n# =============================================================================\n#\n# This is the single Python implementation used by both the subprocess bridge and\n# the embedded Pyodide core. BridgeCodec adds payload-size enforcement around the\n# shared encoder; encode_value is the unbounded form used by the in-memory bridge.\n\ndef _is_nan_or_inf(value):\n if not isinstance(value, (int, float)):\n return False\n try:\n return math.isnan(value) or math.isinf(value)\n except (TypeError, ValueError):\n return False\n\n\ndef _is_numpy_scalar(obj):\n try:\n import numpy as np\n except ImportError:\n return False\n return isinstance(obj, (np.generic, np.ndarray)) and obj.ndim == 0\n\n\ndef _is_pandas_scalar(obj):\n try:\n import pandas as pd\n except ImportError:\n return False\n return isinstance(obj, (pd.Timestamp, pd.Timedelta, type(pd.NaT)))\n\n\ndef make_default_encoder(*, allow_nan):\n \"\"\"\n Build a json.dumps default= encoder matching BridgeCodec's value handling.\n\n Raises CodecError for NaN/Infinity extracted from numpy scalars (json.dumps\n itself rejects top-level/nested NaN/Infinity floats when allow_nan=False).\n \"\"\"\n\n def default_encoder(obj):\n # numpy/pandas scalars first (need .item() extraction).\n if _is_numpy_scalar(obj):\n extracted = obj.item()\n if not allow_nan and _is_nan_or_inf(extracted):\n raise CodecError('Cannot serialize NaN - NaN/Infinity not allowed in JSON')\n return extracted\n\n if _is_pandas_scalar(obj):\n try:\n import pandas as pd\n except ImportError:\n pass\n else:\n if obj is pd.NaT or (hasattr(pd, 'isna') and pd.isna(obj)):\n return None\n if isinstance(obj, pd.Timestamp):\n return obj.isoformat()\n if isinstance(obj, pd.Timedelta):\n return obj.total_seconds()\n\n stdlib_value = serialize_stdlib(obj)\n if stdlib_value is not None:\n return stdlib_value\n\n if isinstance(obj, (bytes, bytearray)):\n return {\n '__type__': 'bytes',\n 'encoding': 'base64',\n 'data': base64.b64encode(obj).decode('ascii'),\n }\n\n model_dump = getattr(obj, 'model_dump', None)\n if callable(model_dump):\n try:\n return model_dump(by_alias=True, mode='json')\n except TypeError:\n return model_dump(by_alias=True)\n\n if isinstance(obj, (set, frozenset)):\n return list(obj)\n\n if isinstance(obj, complex):\n raise TypeError(f'Object of type {type(obj).__name__} is not JSON serializable')\n\n raise TypeError(f'Object of type {type(obj).__name__} is not JSON serializable')\n\n return default_encoder\n\n\ndef encode_value(value, *, allow_nan):\n \"\"\"\n JSON-encode a fully-serialized response value, applying the BridgeCodec-equivalent\n default encoder and rejecting NaN/Infinity when allow_nan is False.\n\n Raises CodecError (wrapping the json.dumps ValueError) on NaN/Infinity, matching\n BridgeCodec's \"Cannot serialize NaN...\" wording so error parity holds.\n \"\"\"\n try:\n return json.dumps(value, default=make_default_encoder(allow_nan=allow_nan), allow_nan=allow_nan)\n except ValueError as exc:\n error_msg = str(exc).lower()\n # json.dumps(allow_nan=False) rejects NaN/Infinity with a ValueError whose\n # wording is Python-version dependent: 3.12+ appends the offending value\n # (\"...not JSON compliant: nan\"), but 3.10/3.11 emit only the canonical\n # \"Out of range float values are not JSON compliant\". Match that phrase too\n # so the typed error message is stable across versions.\n nonfinite_token = re.search(r'(^|[^a-z])(nan|inf|infinity)([^a-z]|$)', error_msg)\n if (\n not allow_nan and 'out of range float values are not json compliant' in error_msg\n ) or nonfinite_token:\n raise CodecError('Cannot serialize NaN - NaN/Infinity not allowed in JSON') from exc\n raise CodecError(f'JSON encoding failed: {exc}') from exc\n except TypeError as exc:\n raise CodecError(f'JSON encoding failed: {exc}') from exc\n\n\nclass BridgeCodec:\n \"\"\"Safe JSON codec with explicit value handling and payload-size limits.\"\"\"\n\n def __init__(self, allow_nan=False, max_payload_bytes=10 * 1024 * 1024):\n self.allow_nan = allow_nan\n self.max_payload_bytes = max_payload_bytes\n self._encoder = make_default_encoder(allow_nan=allow_nan)\n\n def encode(self, value):\n result = encode_value(value, allow_nan=self.allow_nan)\n if len(result.encode('utf-8')) > self.max_payload_bytes:\n raise CodecError(f'Payload exceeds {self.max_payload_bytes} bytes')\n return result\n\n def decode(self, payload):\n if len(payload.encode('utf-8')) > self.max_payload_bytes:\n raise CodecError(f'Payload exceeds {self.max_payload_bytes} bytes')\n try:\n return json.loads(payload)\n except json.JSONDecodeError as exc:\n raise CodecError(f'JSON decoding failed: {exc}') from exc\n\n def _default_encoder(self, obj):\n \"\"\"Compatibility hook for callers that used the codec's JSON encoder.\"\"\"\n return self._encoder(obj)\n\n\n_default_codec = None\n\n\ndef get_default_codec():\n \"\"\"Return the lazily-created default BridgeCodec instance.\"\"\"\n global _default_codec\n if _default_codec is None:\n _default_codec = BridgeCodec()\n return _default_codec\n\n\ndef encode(value, *, allow_nan=False):\n \"\"\"Encode a value with the default codec settings.\"\"\"\n if allow_nan:\n return BridgeCodec(allow_nan=True).encode(value)\n return get_default_codec().encode(value)\n\n\ndef decode(payload):\n \"\"\"Decode a JSON payload with the default codec settings.\"\"\"\n return get_default_codec().decode(payload)\n\n\n# =============================================================================\n# REQUEST VALIDATION + HANDLERS + DISPATCH\n# =============================================================================\n\ndef require_protocol(msg):\n if not isinstance(msg, dict):\n raise ProtocolError('Invalid request payload')\n proto = msg.get('protocol')\n if proto != PROTOCOL:\n raise ProtocolError(f'Invalid protocol: {proto}')\n mid = msg.get('id')\n if not isinstance(mid, int):\n raise ProtocolError(f'Invalid request id: {mid}')\n return mid\n\n\ndef require_str(params, key):\n value = params.get(key)\n if not isinstance(value, str) or not value:\n raise ProtocolError(f'Missing {key}')\n return value\n\n\ndef coerce_list(value, key):\n if value is None:\n return []\n if not isinstance(value, list):\n raise ProtocolError(f'Invalid {key}')\n return value\n\n\ndef coerce_dict(value, key):\n if value is None:\n return {}\n if not isinstance(value, dict):\n raise ProtocolError(f'Invalid {key}')\n return value\n\n\ndef _invoke_call(\n params,\n *,\n allowed_modules,\n allow_private_attrs,\n has_envelope_markers,\n):\n module_name = require_str(params, 'module')\n function_name = require_str(params, 'functionName')\n args = deserialize(coerce_list(params.get('args'), 'args'), has_envelope_markers=has_envelope_markers)\n kwargs = deserialize(coerce_dict(params.get('kwargs'), 'kwargs'), has_envelope_markers=has_envelope_markers)\n mod = import_allowed_module(module_name, allowed_modules)\n # function_name may be dotted ('Class.method') for @classmethod/@staticmethod\n # calls, which the generated wrapper routes through call() rather than an\n # instance handle. resolve_allowed_attr_path guards each segment.\n func = resolve_allowed_attr_path(mod, function_name, allow_private_attrs=allow_private_attrs)\n return func(*args, **kwargs)\n\n\ndef _reject_generator(value):\n import inspect\n\n if inspect.isgenerator(value):\n raise TypeError('Generator results are not supported by tywrap RPC')\n if inspect.isasyncgen(value):\n raise TypeError('Async generator results are not supported by tywrap RPC')\n\n\nasync def _await_result(value):\n return await value\n\n\ndef handle_call(\n params,\n *,\n force_json_markers,\n torch_allow_copy,\n allowed_modules,\n allow_private_attrs,\n has_envelope_markers,\n):\n \"\"\"Run one call. The serial subprocess owns a fresh loop for awaitables.\"\"\"\n import asyncio\n import inspect\n\n res = _invoke_call(\n params,\n allowed_modules=allowed_modules,\n allow_private_attrs=allow_private_attrs,\n has_envelope_markers=has_envelope_markers,\n )\n _reject_generator(res)\n if inspect.isawaitable(res):\n # asyncio.run requires a coroutine, while user code may return any\n # awaitable. It closes the per-call loop on Python 3.10 through 3.12.\n res = asyncio.run(_await_result(res))\n _reject_generator(res)\n return serialize(res, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy)\n\n\nasync def handle_call_async(\n params,\n *,\n force_json_markers,\n torch_allow_copy,\n allowed_modules,\n allow_private_attrs,\n has_envelope_markers,\n):\n \"\"\"Run one call on the caller's loop, which Pyodide owns.\"\"\"\n import inspect\n\n res = _invoke_call(\n params,\n allowed_modules=allowed_modules,\n allow_private_attrs=allow_private_attrs,\n has_envelope_markers=has_envelope_markers,\n )\n _reject_generator(res)\n if inspect.isawaitable(res):\n res = await res\n _reject_generator(res)\n return serialize(res, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy)\n\n\ndef build_meta(\n *,\n bridge,\n pid,\n python_version,\n codec_fallback,\n arrow_available_override=None,\n):\n \"\"\"\n Build the bridge metadata payload.\n\n Field order here is part of the wire contract (the JS validator and the\n documented BridgeInfo shape). Callers supply the backend-specific identity:\n the subprocess server passes bridge='python-subprocess' and a real pid; the\n Pyodide server passes bridge='pyodide' and pid=None.\n\n arrow_available_override: when not None, report this value for arrowAvailable\n instead of probing pyarrow. The Pyodide server forces markers to JSON\n unconditionally, so it advertises arrowAvailable=False regardless of whether\n pyarrow happens to be importable in the WASM environment.\n \"\"\"\n arrow = arrow_available() if arrow_available_override is None else arrow_available_override\n meta = {\n 'protocol': PROTOCOL,\n 'protocolVersion': PROTOCOL_VERSION,\n 'bridge': bridge,\n 'pythonVersion': python_version,\n 'pid': pid,\n 'codecFallback': codec_fallback,\n 'arrowAvailable': arrow,\n 'scipyAvailable': module_available('scipy'),\n 'torchAvailable': module_available('torch'),\n 'sklearnAvailable': module_available('sklearn'),\n 'instances': 0,\n }\n return meta\n\n\ndef dispatch_request(\n msg,\n *,\n bridge,\n pid,\n force_json_markers,\n allow_nan=False,\n python_version=None,\n torch_allow_copy=False,\n arrow_available_override=None,\n allowed_modules=None,\n allow_private_attrs=False,\n has_envelope_markers=True,\n):\n \"\"\"\n Validate and route a request, returning the fully-serialized response dict\n ({'id', 'protocol', 'result'}). Raises ProtocolError for malformed requests\n and propagates handler exceptions to the caller, which is responsible for\n building the error envelope (so it controls traceback inclusion).\n\n allow_nan is accepted for signature symmetry; NaN rejection happens during\n the final encode_value() call, which the caller performs.\n\n allowed_modules: None (default) disables the import allowlist so existing\n behavior is preserved. Supplying a set restricts call imports to\n those modules (plus the stdlib the bridge itself needs) and raises\n ImportNotAllowedError otherwise. allow_private_attrs=False (default) blocks\n getattr of underscore-prefixed names; True restores unrestricted access. See\n the IMPORT / ATTRIBUTE ALLOWLIST section above for the full trust model.\n \"\"\"\n mid = require_protocol(msg)\n method = msg.get('method')\n if not isinstance(method, str):\n raise ProtocolError('Missing method')\n params = coerce_dict(msg.get('params'), 'params')\n if method == 'call':\n result = handle_call(\n params,\n force_json_markers=force_json_markers,\n torch_allow_copy=torch_allow_copy,\n allowed_modules=allowed_modules,\n allow_private_attrs=allow_private_attrs,\n has_envelope_markers=has_envelope_markers,\n )\n elif method == 'meta':\n if python_version is None:\n import sys\n python_version = sys.version.split()[0]\n codec_fallback = 'json' if force_json_markers else 'none'\n result = build_meta(\n bridge=bridge,\n pid=pid,\n python_version=python_version,\n codec_fallback=codec_fallback,\n arrow_available_override=arrow_available_override,\n )\n else:\n raise ProtocolError(f'Unknown method: {method}')\n return {'id': mid, 'protocol': PROTOCOL, 'result': result}\n\n\nasync def dispatch_request_async(\n msg,\n *,\n bridge,\n pid,\n force_json_markers,\n allow_nan=False,\n python_version=None,\n torch_allow_copy=False,\n arrow_available_override=None,\n allowed_modules=None,\n allow_private_attrs=False,\n has_envelope_markers=True,\n):\n \"\"\"Dispatch on the caller's event loop and return one response envelope.\"\"\"\n mid = require_protocol(msg)\n method = msg.get('method')\n if not isinstance(method, str):\n raise ProtocolError('Missing method')\n params = coerce_dict(msg.get('params'), 'params')\n if method == 'call':\n result = await handle_call_async(\n params,\n force_json_markers=force_json_markers,\n torch_allow_copy=torch_allow_copy,\n allowed_modules=allowed_modules,\n allow_private_attrs=allow_private_attrs,\n has_envelope_markers=has_envelope_markers,\n )\n elif method == 'meta':\n if python_version is None:\n import sys\n python_version = sys.version.split()[0]\n codec_fallback = 'json' if force_json_markers else 'none'\n result = build_meta(\n bridge=bridge,\n pid=pid,\n python_version=python_version,\n codec_fallback=codec_fallback,\n arrow_available_override=arrow_available_override,\n )\n else:\n raise ProtocolError(f'Unknown method: {method}')\n return {'id': mid, 'protocol': PROTOCOL, 'result': result}\n\n\ndef build_error_payload(mid, exc, *, include_traceback):\n \"\"\"\n Build a protocol error response. Protocol/validation errors omit traceback;\n handler errors include it. Field order matches the reference server.\n \"\"\"\n error = {'type': type(exc).__name__, 'message': str(exc)}\n if include_traceback:\n error['traceback'] = traceback.format_exc()\n return {\n 'id': mid if mid is not None else -1,\n 'protocol': PROTOCOL,\n 'error': error,\n }\n"; diff --git a/src/runtime/pyodide-transport.ts b/src/runtime/pyodide-transport.ts index 11d2bddc..79564d03 100644 --- a/src/runtime/pyodide-transport.ts +++ b/src/runtime/pyodide-transport.ts @@ -15,7 +15,7 @@ */ import { DisposableBase } from './bounded-context.js'; -import { BridgeProtocolError } from './errors.js'; +import { BridgeDisposedError, BridgeProtocolError, BridgeTimeoutError } from './errors.js'; import { PYODIDE_BRIDGE_CORE_SOURCE } from './pyodide-bootstrap-core.generated.js'; import { PROTOCOL_ID, @@ -100,6 +100,7 @@ export const BOOTSTRAP_PYTHON = ` import sys as __tywrap_sys import json as __tywrap_json import types as __tywrap_types +import asyncio as __tywrap_asyncio # Load the shared bridge core from the embedded source into a real module so the # Pyodide server runs the IDENTICAL protocol/serialization code as the reference @@ -111,9 +112,10 @@ __tywrap_sys.modules[${JSON.stringify(PYODIDE_CORE_MODULE_NAME)}] = __tywrap_cor exec(compile(__tywrap_core_source, '', 'exec'), __tywrap_core.__dict__) __tywrap_protocol = __tywrap_core.PROTOCOL +__tywrap_tasks = {} -def __tywrap_dispatch(message_json): +async def __tywrap_dispatch_task(msg, message_json, mid): """ Dispatch a protocol message and return a JSON response string. @@ -123,13 +125,9 @@ def __tywrap_dispatch(message_json): so NaN/Infinity is rejected with the same wording the subprocess server uses. """ core = __tywrap_core - mid = None try: - msg = __tywrap_json.loads(message_json) - if isinstance(msg, dict) and isinstance(msg.get('id'), int): - mid = msg.get('id') try: - out = core.dispatch_request( + out = await core.dispatch_request_async( msg, bridge='pyodide', pid=None, @@ -143,8 +141,7 @@ def __tywrap_dispatch(message_json): except Exception as e: out = core.build_error_payload(mid, e, include_traceback=True) except Exception as e: - # Malformed JSON / unexpected pre-dispatch failure: well-formed error, - # no traceback (matches the reference's outer handler). + # Unexpected pre-dispatch failure keeps the reference error envelope. out = core.build_error_payload(mid, e, include_traceback=False) try: @@ -160,6 +157,40 @@ def __tywrap_dispatch(message_json): # exactly as the subprocess server's fallback does. err_out = core.build_error_payload(mid, e, include_traceback=False) return __tywrap_json.dumps(err_out) + + +def __tywrap_forget_task(mid, task): + if __tywrap_tasks.get(mid) is task: + __tywrap_tasks.pop(mid, None) + + +def __tywrap_dispatch(message_json): + """Register a task before JavaScript can timeout or abort the call.""" + try: + msg = __tywrap_json.loads(message_json) + except Exception as e: + out = __tywrap_core.build_error_payload(None, e, include_traceback=False) + return __tywrap_json.dumps(out) + + mid = msg.get('id') if isinstance(msg, dict) and isinstance(msg.get('id'), int) else None + if mid is not None and mid in __tywrap_tasks: + error = __tywrap_core.ProtocolError(f'Duplicate request id: {mid}') + out = __tywrap_core.build_error_payload(mid, error, include_traceback=False) + return __tywrap_json.dumps(out) + + task = __tywrap_asyncio.get_event_loop().create_task( + __tywrap_dispatch_task(msg, message_json, mid) + ) + if mid is not None: + __tywrap_tasks[mid] = task + task.add_done_callback(lambda done: __tywrap_forget_task(mid, done)) + return task + + +def __tywrap_cancel(mid): + """Request cooperative cancellation of one active RPC task.""" + task = __tywrap_tasks.get(mid) + return task.cancel() if task is not None else False `; // ============================================================================= @@ -196,6 +227,7 @@ export class PyodideTransport extends DisposableBase implements Transport { private readonly indexURL: string; private readonly packages: readonly string[]; private py?: PyodideInstance; + private readonly activeCalls = new Map void; dispose: () => void }>(); /** * Create a new PyodideTransport. @@ -248,6 +280,9 @@ export class PyodideTransport extends DisposableBase implements Transport { * We clear our reference and rely on garbage collection. */ protected async doDispose(): Promise { + for (const call of this.activeCalls.values()) { + call.dispose(); + } this.py = undefined; } @@ -284,7 +319,11 @@ export class PyodideTransport extends DisposableBase implements Transport { ): Promise { return this.execute( async () => { - if (!this.py) { + const py = this.py; + if (this.state === 'disposing' || this.state === 'disposed') { + throw new BridgeDisposedError('Transport disposed'); + } + if (!py) { throw new BridgeProtocolError('Pyodide not initialized'); } @@ -306,41 +345,110 @@ export class PyodideTransport extends DisposableBase implements Transport { if (!parsed.params || typeof parsed.params !== 'object' || Array.isArray(parsed.params)) { throw new BridgeProtocolError('Message missing required fields: id, method'); } + if (this.activeCalls.has(parsed.id)) { + throw new BridgeProtocolError(`Duplicate request id: ${parsed.id}`); + } // Get the dispatch function - const dispatchFn = this.py.globals.get('__tywrap_dispatch'); + const dispatchFn = py.globals.get('__tywrap_dispatch'); if (!dispatchFn) { throw new BridgeProtocolError('Pyodide dispatch function not initialized'); } + let result: string | PromiseLike; try { - // Call the dispatch function - const invoke = dispatchFn as (messageJson: string) => string; - const responseJson = invoke(message); + result = (dispatchFn as (messageJson: string) => string | PromiseLike)(message); + } catch (error) { + this.destroyPyProxy(dispatchFn); + throw error; + } - // Validate response is valid JSON + const cancel = (): void => { + let cancelFn: unknown; try { - const response = JSON.parse(responseJson) as ProtocolResponse; - if (typeof response.id !== 'number' || !Number.isInteger(response.id)) { - throw new BridgeProtocolError('Invalid response from Python: missing numeric id'); - } - if (response.protocol !== undefined && response.protocol !== PROTOCOL_ID) { - throw new BridgeProtocolError( - `Invalid protocol version: expected "${PROTOCOL_ID}", got "${response.protocol}"` - ); + cancelFn = py.globals.get('__tywrap_cancel'); + if (typeof cancelFn === 'function') { + (cancelFn as (id: number) => unknown)(parsed.id); } - if (response.error) { - // Return the response as-is; let the caller handle the error - return responseJson; - } - return responseJson; + } catch { + // A timeout or disposal must retain its original error. + } finally { + this.destroyPyProxy(cancelFn); + } + }; + + let rejectEarly: (error: Error) => void = () => {}; + const interrupted = new Promise((_resolve, reject) => { + rejectEarly = reject; + }); + let finished = false; + let timer: ReturnType | undefined; + const stopTimer = (): void => { + if (timer !== undefined) { + clearTimeout(timer); + } + signal?.removeEventListener('abort', onAbort); + }; + const interrupt = (error: Error): void => { + if (finished) { + return; + } + finished = true; + stopTimer(); + cancel(); + rejectEarly(error); + }; + const onAbort = (): void => interrupt(new BridgeTimeoutError('Operation aborted')); + + const completion = Promise.resolve(result).then(responseJson => { + let response: ProtocolResponse; + try { + response = JSON.parse(responseJson) as ProtocolResponse; } catch { throw new BridgeProtocolError(`Invalid JSON response from Python: ${responseJson}`); } - } finally { - // Clean up the proxy + if (typeof response.id !== 'number' || !Number.isInteger(response.id)) { + throw new BridgeProtocolError('Invalid response from Python: missing numeric id'); + } + if (response.id !== parsed.id) { + throw new BridgeProtocolError( + `Invalid response id: expected ${parsed.id}, got ${response.id}` + ); + } + if (response.protocol !== undefined && response.protocol !== PROTOCOL_ID) { + throw new BridgeProtocolError( + `Invalid protocol version: expected "${PROTOCOL_ID}", got "${response.protocol}"` + ); + } + return responseJson; + }); + + // This handler owns proxy cleanup even if the caller's timeout wins. + const cleanup = (): void => { + finished = true; + stopTimer(); + this.activeCalls.delete(parsed.id); + this.destroyPyProxy(result); this.destroyPyProxy(dispatchFn); + }; + completion.then(cleanup, cleanup); + + this.activeCalls.set(parsed.id, { + cancel, + dispose: () => interrupt(new BridgeDisposedError('Transport disposed')), + }); + if (timeoutMs > 0 && Number.isFinite(timeoutMs)) { + timer = setTimeout( + () => interrupt(new BridgeTimeoutError(`Operation timed out after ${timeoutMs}ms`)), + timeoutMs + ); + } + signal?.addEventListener('abort', onAbort, { once: true }); + if (signal?.aborted) { + onAbort(); } + + return Promise.race([completion, interrupted]); }, { timeoutMs, signal } ); diff --git a/src/runtime/rpc-client.ts b/src/runtime/rpc-client.ts index 3eee208f..38409227 100644 --- a/src/runtime/rpc-client.ts +++ b/src/runtime/rpc-client.ts @@ -23,6 +23,7 @@ import type { BridgeBackend, BridgeInfo } from '../types/index.js'; import { DisposableBase, type ExecuteOptions } from './bounded-context.js'; import { BridgeProtocolError } from './errors.js'; import { BridgeCodec, type CodecOptions } from './bridge-codec.js'; +import { DecodedProvenance } from './decoded-provenance.js'; import { PROTOCOL_ID, TYWRAP_PROTOCOL_VERSION, @@ -329,9 +330,8 @@ export class RpcClient extends DisposableBase { * supplies auto-init and exactly-one-attempt timeout/abort handling), where the only difference between * the sync and Arrow-aware paths is the supplied `decode` step. * - * Behavior-preserving extraction of the two twins; ordering, the - * `options?.timeoutMs ?? this.defaultTimeoutMs` fallback, and the - * `this.execute(..., options)` wrapping are unchanged. + * The transport gets the configured timeout. The outer bound adds one + * second so transport errors can include details such as Python stderr. */ private async sendVia( message: Omit, @@ -339,22 +339,28 @@ export class RpcClient extends DisposableBase { decode: (responseStr: string) => T | Promise ): Promise { const fullMessage = this.stampMessage(message); - - return this.execute(async () => { - // 1. Encode request (validates args) - const encoded = this.codec.encodeRequest(fullMessage); - - // 2. Send via transport - const responseStr = await this.transport.send( - encoded, - options?.timeoutMs ?? this.defaultTimeoutMs, - options?.signal, - fullMessage.id - ); - - // 3. Decode response (sync or Arrow-aware, per caller) - return decode(responseStr); - }, options); + const transportTimeoutMs = options?.timeoutMs ?? this.defaultTimeoutMs; + // Let the transport report its own timeout, including Python stderr. + const executionTimeoutMs = transportTimeoutMs > 0 ? transportTimeoutMs + 1_000 : 0; + + return this.execute( + async () => { + // 1. Encode request (validates args) + const encoded = this.codec.encodeRequest(fullMessage); + + // 2. Send via transport + const responseStr = await this.transport.send( + encoded, + transportTimeoutMs, + options?.signal, + fullMessage.id + ); + + // 3. Decode response (sync or Arrow-aware, per caller) + return decode(responseStr); + }, + { ...options, timeoutMs: executionTimeoutMs } + ); } /** @@ -431,9 +437,10 @@ export class RpcClient extends DisposableBase { functionName: string, args: unknown[], kwargs?: Record, - validate?: (result: T) => void + validate?: (result: T, provenance?: DecodedProvenance) => void ): Promise { - return this.sendMessageAsync( + const provenance = validate ? new DecodedProvenance() : undefined; + return this.sendVia( { method: 'call', params: { @@ -446,11 +453,12 @@ export class RpcClient extends DisposableBase { validate ? { validate: result => { - validate(result); + validate(result, provenance); return result; }, } - : undefined + : undefined, + responseStr => this.codec.decodeResponseAsync(responseStr, provenance) ); } diff --git a/src/runtime/subprocess-transport.ts b/src/runtime/subprocess-transport.ts index 39003c05..105c56ae 100644 --- a/src/runtime/subprocess-transport.ts +++ b/src/runtime/subprocess-transport.ts @@ -117,6 +117,7 @@ interface PendingRequest { resolve: (value: string) => void; reject: (error: Error) => void; timer?: NodeJS.Timeout; + written?: boolean; } /** @@ -137,6 +138,7 @@ interface QueuedWrite { * (and so never executes on) Python. */ isLive?: () => boolean; + onWrite?: () => void; /** True while this entry is waiting to be flushed. */ isQueued?: boolean; } @@ -264,6 +266,17 @@ export class SubprocessTransport extends DisposableBase implements Transport { private process: ChildProcess | null = null; private processExited = false; private processError: Error | null = null; + private readonly shutdownHandlers = new WeakSet(); + private readonly processErrorListener = (error: Error): void => this.handleProcessError(error); + private readonly stdoutDataListener = (chunk: Buffer | string): void => + this.handleStdoutData(chunk); + private readonly stdoutErrorListener = (error: Error): void => this.handleStdoutError(error); + private readonly stderrDataListener = (chunk: Buffer | string): void => + this.handleStderrData(chunk); + private readonly stderrErrorListener = (error: Error): void => this.handleStderrError(error); + private readonly stdinErrorListener = (error: Error): void => this.handleStdinError(error); + private readonly stdinDrainListener = (): void => this.handleStdinDrain(); + private disposalInFlight?: Promise; // Stream buffers private stdoutBuffer = ''; @@ -277,6 +290,8 @@ export class SubprocessTransport extends DisposableBase implements Transport { }); private requestCount = 0; private needsRestart = false; + private retiredGeneration = false; + private retirement?: Promise; /** Serializes restart decisions with dispatch reservations. */ private dispatchMutex: Promise = Promise.resolve(); private activeDispatches = 0; @@ -321,6 +336,11 @@ export class SubprocessTransport extends DisposableBase implements Transport { }); } + /** Whether a timed-out or aborted request retired this process generation. */ + get requiresReplacement(): boolean { + return this.retiredGeneration; + } + // =========================================================================== // TRANSPORT INTERFACE // =========================================================================== @@ -350,7 +370,7 @@ export class SubprocessTransport extends DisposableBase implements Transport { } // Check if process is alive - if (this.processExited || !this.process) { + if ((this.processExited || !this.process) && !this.needsRestart) { const stderrTail = this.getStderrTail(); const baseMsg = 'Python process is not running'; const msg = stderrTail ? `${baseMsg}. Stderr:\n${stderrTail}` : baseMsg; @@ -382,35 +402,36 @@ export class SubprocessTransport extends DisposableBase implements Transport { // Set up timeout if specified let timer: NodeJS.Timeout | undefined; - // Defined before the timer so the timeout path can also detach it. - const abortHandler = (): void => { + const abandon = (error: BridgeTimeoutError): void => { + if (this.pending.get(messageId) !== pendingEntry) { + return; + } if (timer) { clearTimeout(timer); } + signal?.removeEventListener('abort', abortHandler); this.pending.delete(messageId); this.timedOutRequests.mark(messageId); - // Same late-frame discard as the timeout path (see below). this.responseReassembler?.discard(messageId); - reject(new BridgeTimeoutError('Operation aborted')); + reject(error); + // A request that reached Python may run forever. Retire only that + // process generation; a queued, unwritten request leaves it intact. + if (pendingEntry.written) { + this.retireProcessGeneration(); + } + }; + + // Defined before the timer so the timeout path can also detach it. + const abortHandler = (): void => { + abandon(new BridgeTimeoutError('Operation aborted')); }; if (timeoutMs > 0) { timer = setTimeout(() => { - this.pending.delete(messageId); - this.timedOutRequests.mark(messageId); - // Discard any in-flight chunked response stream for this id so late - // frames are dropped rather than desyncing stdout (the single-line - // timedOutRequests.consume above is one-shot and insufficient for a - // multi-frame stream). - this.responseReassembler?.discard(messageId); - // Detach the abort listener: on timeout the abort never fires, so - // without this it would leak on a long-lived AbortSignal and could - // re-enter abortHandler after this promise has already settled. - signal?.removeEventListener('abort', abortHandler); const stderrTail = this.getStderrTail(); const baseMsg = `Operation timed out after ${timeoutMs}ms`; const msg = stderrTail ? `${baseMsg}. Recent stderr:\n${stderrTail}` : baseMsg; - reject(new BridgeTimeoutError(msg)); + abandon(new BridgeTimeoutError(msg)); }, timeoutMs); } @@ -466,7 +487,9 @@ export class SubprocessTransport extends DisposableBase implements Transport { return this.writeRequest(message, messageId, signal, pendingEntry); }) .catch(err => { - this.pending.delete(messageId); + if (this.pending.get(messageId) === pendingEntry) { + this.pending.delete(messageId); + } if (timer) { clearTimeout(timer); } @@ -576,6 +599,27 @@ export class SubprocessTransport extends DisposableBase implements Transport { await this.spawnProcess(); } + /** Retry cleanup if the first disposal could not reap the child. */ + override dispose(): Promise { + if (this.disposalInFlight) { + return this.disposalInFlight; + } + const disposal = + this.isDisposed && this.process + ? this.withDispatchMutex(() => this.killProcess()) + : super.dispose(); + this.disposalInFlight = disposal; + disposal.then( + () => { + this.disposalInFlight = undefined; + }, + () => { + this.disposalInFlight = undefined; + } + ); + return disposal; + } + /** * Dispose the transport by killing the Python process. */ @@ -599,7 +643,14 @@ export class SubprocessTransport extends DisposableBase implements Transport { // Fence queued restart work before killing the process. A restart already // holding the mutex observes the disposing state before it can spawn; if it // spawned just before disposal began, this barrier kills that child too. - await this.withDispatchMutex(() => this.killProcess()); + await this.withDispatchMutex(async () => { + try { + await this.retirement; + } catch { + // Retry the retained process handle during final disposal. + } + await this.killProcess(); + }); // Clear buffers this.stdoutBuffer = ''; @@ -660,22 +711,22 @@ export class SubprocessTransport extends DisposableBase implements Transport { this.processError = null; // Set up event handlers - this.process.on('error', this.handleProcessError.bind(this)); + this.process.on('error', this.processErrorListener); this.process.on('exit', this.handleProcessExit.bind(this)); if (this.process.stdout) { - this.process.stdout.on('data', this.handleStdoutData.bind(this)); - this.process.stdout.on('error', this.handleStdoutError.bind(this)); + this.process.stdout.on('data', this.stdoutDataListener); + this.process.stdout.on('error', this.stdoutErrorListener); } if (this.process.stderr) { - this.process.stderr.on('data', this.handleStderrData.bind(this)); - this.process.stderr.on('error', this.handleStderrError.bind(this)); + this.process.stderr.on('data', this.stderrDataListener); + this.process.stderr.on('error', this.stderrErrorListener); } if (this.process.stdin) { - this.process.stdin.on('drain', this.handleStdinDrain.bind(this)); - this.process.stdin.on('error', this.handleStdinError.bind(this)); + this.process.stdin.on('drain', this.stdinDrainListener); + this.process.stdin.on('error', this.stdinErrorListener); } // Wait for process to be ready (first heartbeat could be here) @@ -693,14 +744,26 @@ export class SubprocessTransport extends DisposableBase implements Transport { const proc = this.process; this.process = null; + this.processExited = true; - // Add a catch-all error handler to prevent uncaught exceptions during shutdown - // This must be added BEFORE removing other listeners and ending stdin - const noopErrorHandler = (): void => { - // Ignore errors during shutdown (e.g., EPIPE) - }; - proc.stdin?.on('error', noopErrorHandler); - proc.on('error', noopErrorHandler); + // Keep shutdown errors handled without letting the retired child change a new process. + if (!this.shutdownHandlers.has(proc)) { + const noopErrorHandler = (): void => { + // Ignore errors during shutdown (e.g., EPIPE) + }; + proc.stdin?.on('error', noopErrorHandler); + proc.on('error', noopErrorHandler); + proc.stdout?.on('error', noopErrorHandler); + proc.stderr?.on('error', noopErrorHandler); + proc.stdin?.removeListener('error', this.stdinErrorListener); + proc.removeListener('error', this.processErrorListener); + proc.stdin?.removeListener('drain', this.stdinDrainListener); + proc.stdout?.removeListener('data', this.stdoutDataListener); + proc.stdout?.removeListener('error', this.stdoutErrorListener); + proc.stderr?.removeListener('data', this.stderrDataListener); + proc.stderr?.removeListener('error', this.stderrErrorListener); + this.shutdownHandlers.add(proc); + } // Gracefully end stdin to prevent EPIPE on pending writes try { @@ -709,31 +772,71 @@ export class SubprocessTransport extends DisposableBase implements Transport { // Ignore errors ending stdin } - // Remove other listeners to prevent callbacks after disposal + // Remove live exit callbacks before waiting for this child to exit. proc.removeAllListeners('exit'); proc.removeAllListeners('close'); - proc.stdout?.removeAllListeners(); - proc.stderr?.removeAllListeners(); - - // Kill the process - if (!proc.killed) { - proc.kill('SIGTERM'); - - // Wait briefly for graceful exit - await new Promise(resolve => { - const timeout = setTimeout(() => { - if (!proc.killed) { - proc.kill('SIGKILL'); - } - resolve(); - }, 1000); - proc.once('exit', () => { - clearTimeout(timeout); - resolve(); - }); - }); + const hasExited = (): boolean => + (proc.exitCode !== null && proc.exitCode !== undefined) || + (proc.signalCode !== null && proc.signalCode !== undefined); + if (hasExited()) { + return; } + + await new Promise((resolve, reject) => { + const timers: { + grace?: ReturnType; + force?: ReturnType; + } = {}; + const finish = (error?: Error): void => { + if (timers.grace) { + clearTimeout(timers.grace); + } + if (timers.force) { + clearTimeout(timers.force); + } + proc.removeListener('exit', onExit); + if (error) { + // Keep the handle for a later disposal retry. Never publish a new + // generation while the old child may still be alive. + this.process = proc; + reject(error); + } else { + resolve(); + } + }; + const onExit = (): void => finish(); + proc.once('exit', onExit); + if (hasExited()) { + finish(); + return; + } + if (!proc.killed) { + try { + proc.kill('SIGTERM'); + } catch { + // The force timer below still bounds shutdown. + } + } + timers.grace = setTimeout(() => { + if (hasExited()) { + finish(); + return; + } + try { + proc.kill('SIGKILL'); + } catch { + // Report an unreaped child after the force deadline. + } + timers.force = setTimeout(() => { + if (hasExited()) { + finish(); + } else { + finish(new BridgeProtocolError('Python process did not exit after SIGKILL')); + } + }, 1000); + }, 1000); + }); } /** @@ -744,6 +847,14 @@ export class SubprocessTransport extends DisposableBase implements Transport { throw new BridgeDisposedError('Transport has been disposed'); } + await this.retirement; + this.retirement = undefined; + + // Old queued writes belong to the old stdin, even if it never drained. + this.rejectAllQueuedWrites( + new BridgeProtocolError('Python worker restarted before queued writes completed') + ); + // Kill existing process await this.killProcess(); @@ -753,6 +864,7 @@ export class SubprocessTransport extends DisposableBase implements Transport { this.stderrBuffer = ''; this.requestCount = 0; this.needsRestart = false; + this.draining = false; // Drop any partial reassembly + discard tracking: the new process owns a // fresh stdout stream, so stale per-id state from the dead process must not // leak across the restart boundary. @@ -772,6 +884,7 @@ export class SubprocessTransport extends DisposableBase implements Transport { // Spawn a fresh process with the packaged always-on framing protocol. await this.spawnProcess(); + this.retiredGeneration = false; } /** @@ -783,6 +896,22 @@ export class SubprocessTransport extends DisposableBase implements Transport { this.needsRestart = true; } + private retireProcessGeneration(): void { + if (this.retiredGeneration || this.isLifecycleEnding()) { + return; + } + this.retiredGeneration = true; + this.needsRestart = true; + const error = new BridgeProtocolError('Python worker retired after request timeout or abort'); + this.rejectAllPending(error); + this.rejectAllQueuedWrites(error); + // killProcess removes old stdout listeners before a replacement can start. + this.retirement = this.killProcess(); + this.retirement.catch(() => { + this.processExited = true; + }); + } + // =========================================================================== // STREAM HANDLERS // =========================================================================== @@ -1073,10 +1202,11 @@ export class SubprocessTransport extends DisposableBase implements Transport { data: string, resolve: () => void, reject: (error: Error) => void, - isLive?: () => boolean + isLive?: () => boolean, + onWrite?: () => void ): QueuedWrite { const queuedAt = Date.now(); - const entry: QueuedWrite = { data, resolve, reject, queuedAt, isLive, isQueued: true }; + const entry: QueuedWrite = { data, resolve, reject, queuedAt, isLive, onWrite, isQueued: true }; // Set up timeout timer that fires if drain never happens entry.timeoutHandle = setTimeout(() => { @@ -1111,7 +1241,7 @@ export class SubprocessTransport extends DisposableBase implements Transport { /** * Write data to stdin with backpressure handling. */ - private writeToStdin(data: string, isLive?: () => boolean): Promise { + private writeToStdin(data: string, isLive?: () => boolean, onWrite?: () => void): Promise { return new Promise((resolve, reject) => { if (!this.process?.stdin || this.processExited) { reject(new BridgeProtocolError(this.withStderrTail('Process stdin not available'))); @@ -1121,7 +1251,7 @@ export class SubprocessTransport extends DisposableBase implements Transport { if (this.draining || this.writeQueue.length > this.writeQueueHead) { // Queue the write with timestamp, timeout timer, and liveness predicate // (checked again at flush — see processQueuedWrite). - this.writeQueue.push(this.createQueuedWrite(data, resolve, reject, isLive)); + this.writeQueue.push(this.createQueuedWrite(data, resolve, reject, isLive, onWrite)); return; } @@ -1134,6 +1264,7 @@ export class SubprocessTransport extends DisposableBase implements Transport { // Try direct write (wrap in try-catch for synchronous EPIPE errors) try { + onWrite?.(); const canWrite = this.process.stdin.write(data); if (canWrite) { @@ -1193,6 +1324,11 @@ export class SubprocessTransport extends DisposableBase implements Transport { (pendingEntry !== undefined ? this.pending.get(messageId) === pendingEntry : this.pending.has(messageId)); + const onWrite = (): void => { + if (pendingEntry) { + pendingEntry.written = true; + } + }; const run = (): Promise => { if (!isLive()) { return Promise.resolve(); @@ -1200,9 +1336,9 @@ export class SubprocessTransport extends DisposableBase implements Transport { // Chunk when the encoded request exceeds the fixed per-frame ceiling // supplied to the packaged Python peer. Otherwise use one JSONL line. if (utf8ByteLength(message) > this.frameBytes) { - return this.writeChunkedRequest(message, messageId, signal, isLive); + return this.writeChunkedRequest(message, messageId, signal, isLive, onWrite); } - return this.writeToStdin(`${message}\n`, isLive); + return this.writeToStdin(`${message}\n`, isLive, onWrite); }; // Serialize the whole logical write onto the mutex tail. We chain the next @@ -1231,7 +1367,8 @@ export class SubprocessTransport extends DisposableBase implements Transport { message: string, messageId: number, signal?: AbortSignal, - isLive?: () => boolean + isLive?: () => boolean, + onWrite?: () => void ): Promise { const frames = encodeFrames(message, { id: messageId, @@ -1252,7 +1389,7 @@ export class SubprocessTransport extends DisposableBase implements Transport { // One frame per JSONL line; await each so stdin backpressure is honored. // isLive gates a frame that ends up queued under backpressure past a late // cancellation, so an abandoned chunked request never completes on Python. - await this.writeToStdin(`${JSON.stringify(frame)}\n`, isLive); + await this.writeToStdin(`${JSON.stringify(frame)}\n`, isLive, onWrite); } } @@ -1307,6 +1444,7 @@ export class SubprocessTransport extends DisposableBase implements Transport { } try { + queued.onWrite?.(); const canWrite = stdin.write(queued.data); if (canWrite) { diff --git a/src/runtime/validators.ts b/src/runtime/validators.ts index c3ade3e0..c0b56bbb 100644 --- a/src/runtime/validators.ts +++ b/src/runtime/validators.ts @@ -1,6 +1,9 @@ import { BridgeValidationError } from './errors.js'; +import type { DecodedProvenance, DecodedShapeMetadata } from './decoded-provenance.js'; import type { ScientificMarker } from '../utils/codec.js'; +export type { DecodedShapeMetadata } from './decoded-provenance.js'; + /** * Pure validation functions for runtime value checking. * @@ -23,7 +26,16 @@ export type ReturnSchema = | { kind: 'any' } | { kind: 'primitive'; - type: 'number' | 'string' | 'boolean' | 'null' | 'undefined' | 'Uint8Array' | 'object'; + type: + | 'number' + | 'bigint' + | 'string' + | 'boolean' + | 'null' + | 'undefined' + | 'Uint8Array' + | 'object'; + constraint?: 'safe-integer' | 'finite'; } | { kind: 'literal'; value: string | number | boolean | null } | { kind: 'array'; element: ReturnSchema } @@ -42,12 +54,26 @@ export type ReturnSchema = dtype?: string; }; -export type ReturnValidator = (result: T) => T; +export type ReturnValidator = (result: T, provenance?: DecodedProvenance) => T; + +/** One Python parameter used to select a declared overload after call binding. */ +export interface OverloadParameterSchema { + name: string; + kind: + | 'positional-only' + | 'positional-or-keyword' + | 'var-positional' + | 'keyword-only' + | 'var-keyword'; + optional: boolean; + value: ReturnSchema; +} -export interface DecodedShapeMetadata { - marker: ScientificMarker; - dims?: number; - dtype?: string; +/** An overload is selectable only when all of its value rules are supported. */ +export interface OverloadReturnSchema { + parameters: readonly OverloadParameterSchema[]; + result: ReturnSchema; + selectable: boolean; } const decodedShapeMetadata = new WeakMap(); @@ -99,7 +125,7 @@ function renderSchema(schema: ReturnSchema): string { case 'any': return 'unknown'; case 'primitive': - return schema.type; + return schema.constraint ?? schema.type; case 'literal': return JSON.stringify(schema.value); case 'array': @@ -120,9 +146,20 @@ function renderSchema(schema: ReturnSchema): string { interface CheckState { readonly definitions: Readonly>; readonly pairs: WeakMap>; + readonly provenance?: DecodedProvenance; } -function check(schema: ReturnSchema, value: unknown, state: CheckState): boolean { +interface ValueLocation { + parent: object; + key: string | number; +} + +function check( + schema: ReturnSchema, + value: unknown, + state: CheckState, + location?: ValueLocation +): boolean { if (schema.kind === 'any') { return true; } @@ -140,7 +177,7 @@ function check(schema: ReturnSchema, value: unknown, state: CheckState): boolean seen.add(schema.name); state.pairs.set(value, seen); } - return check(definition, value, state); + return check(definition, value, state, location); } switch (schema.kind) { @@ -157,16 +194,29 @@ function check(schema: ReturnSchema, value: unknown, state: CheckState): boolean if (schema.type === 'object') { return isPlainObject(value); } + if (schema.type === 'number' && schema.constraint === 'safe-integer') { + return typeof value === 'number' && Number.isSafeInteger(value); + } + if (schema.type === 'number' && schema.constraint === 'finite') { + return typeof value === 'number' && Number.isFinite(value); + } return typeof value === schema.type; case 'literal': return Object.is(value, schema.value); case 'array': - return Array.isArray(value) && value.every(item => check(schema.element, item, state)); + return ( + Array.isArray(value) && + value.every((item, index) => + check(schema.element, item, state, { parent: value, key: index }) + ) + ); case 'tuple': return ( Array.isArray(value) && value.length === schema.elements.length && - schema.elements.every((entry, index) => check(entry, value[index], state)) + schema.elements.every((entry, index) => + check(entry, value[index], state, { parent: value, key: index }) + ) ); case 'record': { if (!isPlainObject(value)) { @@ -180,20 +230,26 @@ function check(schema: ReturnSchema, value: unknown, state: CheckState): boolean } return false; } - if (!check(field.schema, value[key], state)) { + if (!check(field.schema, value[key], state, { parent: value, key })) { return false; } } } return ( !schema.values || - Object.values(value).every(item => check(schema.values as ReturnSchema, item, state)) + Object.entries(value).every(([key, item]) => + check(schema.values as ReturnSchema, item, state, { parent: value, key }) + ) ); } case 'union': - return schema.options.some(option => check(option, value, state)); + return schema.options.some(option => check(option, value, state, location)); case 'marker': { - const metadata = isObjectLike(value) ? decodedShapeMetadata.get(value) : undefined; + const metadata = isObjectLike(value) + ? decodedShapeMetadata.get(value) + : location + ? state.provenance?.atChild(location.parent, location.key) + : state.provenance?.atRoot(); if (metadata?.marker !== schema.marker) { return false; } @@ -215,8 +271,10 @@ export function createReturnValidator( definitions: Readonly> = {} ): ReturnValidator { const declaredType = renderSchema(schema); - return (result: T): T => { - if (!check(schema, result, { definitions, pairs: new WeakMap>() })) { + return (result: T, provenance?: DecodedProvenance): T => { + if ( + !check(schema, result, { definitions, pairs: new WeakMap>(), provenance }) + ) { throw new BridgeValidationError({ declaredType, receivedShape: describeReceivedShape(result), @@ -227,6 +285,81 @@ export function createReturnValidator( }; } +function matchesOverload( + signature: OverloadReturnSchema, + args: readonly unknown[], + kwargs: Readonly> | undefined +): boolean { + if (!signature.selectable) { + return false; + } + const keywords = kwargs ?? {}; + const usedKeywords = new Set(); + let position = 0; + let acceptsOtherKeywords = false; + const matches = (schema: ReturnSchema, value: unknown): boolean => + check(schema, value, { definitions: {}, pairs: new WeakMap>() }); + + for (const parameter of signature.parameters) { + if (parameter.kind === 'var-positional') { + while (position < args.length) { + if (!matches(parameter.value, args[position])) { + return false; + } + position += 1; + } + continue; + } + if (parameter.kind === 'var-keyword') { + acceptsOtherKeywords = true; + for (const [name, value] of Object.entries(keywords)) { + if (!usedKeywords.has(name) && !matches(parameter.value, value)) { + return false; + } + } + continue; + } + const hasPosition = parameter.kind !== 'keyword-only' && position < args.length; + const hasKeyword = Object.prototype.hasOwnProperty.call(keywords, parameter.name); + if (hasKeyword && parameter.kind === 'positional-only') { + return false; + } + if (hasPosition && hasKeyword) { + return false; + } + if (!hasPosition && !hasKeyword) { + if (!parameter.optional) { + return false; + } + continue; + } + const value = hasPosition ? args[position++] : keywords[parameter.name]; + if (hasKeyword) { + usedKeywords.add(parameter.name); + } + if (!matches(parameter.value, value)) { + return false; + } + } + if (position < args.length) { + return false; + } + return acceptsOtherKeywords || Object.keys(keywords).every(name => usedKeywords.has(name)); +} + +/** Select the first supported match, as TypeScript does for declared overloads. */ +export function selectOverloadReturnValidator( + overloads: readonly OverloadReturnSchema[], + args: readonly unknown[], + kwargs: Readonly> | undefined, + fallback: ReturnValidator, + callSite: string, + definitions: Readonly> = {} +): ReturnValidator { + const selected = overloads.find(overload => matchesOverload(overload, args, kwargs)); + return selected ? createReturnValidator(selected.result, callSite, definitions) : fallback; +} + // ═══════════════════════════════════════════════════════════════════════════ // TYPE GUARDS // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/types/index.ts b/src/types/index.ts index c5b0d408..b717b0fb 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -2,6 +2,9 @@ * Core type definitions for tywrap */ +import type { ValueContractV3 } from '../contracts/value-contract.js'; +import type { DecodedProvenance } from '../runtime/decoded-provenance.js'; + export interface PythonModule { name: string; path?: string; @@ -40,6 +43,21 @@ export interface PythonFunction { typeParameters?: PythonGenericParameter[]; returnType: PythonType; parameters: Parameter[]; + /** + * Distinct callable signatures extracted from `@typing.overload`. + * + * The implementation signature stays in `parameters` and `returnType` for + * runtime binding. Each overload retains its own input-to-result relation for + * generated declarations. + */ + overloads?: PythonFunctionOverload[]; + /** + * Internal value contracts resolved before code emission. + * + * The compiler sets this field. Parser-created models leave it absent, and + * the generator then uses its legacy schema derivation. + */ + callableContract?: ResolvedCallableContract; /** * Binding of this callable on its owning class. Defaults to `'instance'`. * @see PythonMethodKind @@ -47,6 +65,24 @@ export interface PythonFunction { methodKind?: PythonMethodKind; } +export interface PythonFunctionOverload { + parameters: Parameter[]; + returnType: PythonType; +} + +/** A resolved value contract for a callable signature. */ +export interface ResolvedCallableSignatureContract { + parameterValues: readonly (ValueContractV3 | undefined)[]; + returnValue?: ValueContractV3; + /** Original annotation used for best-effort validation when no value contract resolves. */ + returnValidationType?: PythonType; +} + +/** Internal compiler data consumed by generated validators. */ +export interface ResolvedCallableContract extends ResolvedCallableSignatureContract { + overloads: readonly ResolvedCallableSignatureContract[]; +} + /** * A `@property` or `functools.cached_property` exposed on a class. * @@ -503,7 +539,7 @@ export interface PythonRuntime { functionName: string, args: unknown[], kwargs?: Record, - validate?: (result: T) => void + validate?: (result: T, provenance?: DecodedProvenance) => void ): Promise; } diff --git a/src/tywrap.ts b/src/tywrap.ts index 4e079c4f..f31deeee 100644 --- a/src/tywrap.ts +++ b/src/tywrap.ts @@ -3,20 +3,23 @@ */ import { CodeGenerator } from './core/generator.js'; +import { + compileContract, + DEFAULT_CALLABLE_CAPABILITIES, + DEFAULT_VALUE_CONVERSION, +} from './core/callable-compiler.js'; +import { + TYWRAP_IR_VERSION, + validateIrContract, + type ValidatedIrContract, +} from './core/ir-contract.js'; +import { transformIrToTsModel } from './core/ir-model.js'; import { TypeMapper } from './core/mapper.js'; -import { parseAnnotationToPythonType } from './core/annotation-parser.js'; import { createConfig } from './config/index.js'; import type { TywrapOptions, - PythonGenericParameter, - PythonFunction, PythonModule as TSPythonModule, - PythonClass, - PythonTypeAlias, - Parameter, - PythonType, PythonModuleConfig, - IrContract, } from './types/index.js'; import { fsUtils, pathUtils, processUtils, isWindows } from './utils/runtime.js'; import { globalCache } from './utils/cache.js'; @@ -24,8 +27,6 @@ import { resolvePythonExecutable } from './utils/python.js'; import { computeIrCacheFilename } from './utils/ir-cache.js'; import { logger } from './utils/logger.js'; -const TYWRAP_IR_VERSION = '0.4.0'; - // Collect unknown typing constructs encountered during annotation parsing (per-generate run) let unknownTypeNamesCollector: Map = new Map(); function recordUnknown(name: string): void { @@ -101,52 +102,25 @@ function stableJson(value: unknown): unknown { return value; } -function serializeContract(ir: IrContract): string { - const contract = { ...ir }; - delete contract.metadata; +function serializeContract(ir: ValidatedIrContract): string { + const contract = Object.fromEntries(Object.entries(ir).filter(([key]) => key !== 'metadata')); return `${JSON.stringify(stableJson(contract), null, 2)}\n`; } function validateIrVersion( ir: unknown, source: string -): { ir: IrContract | null; error?: string; code?: GenerateFailure['code'] } { - if (ir === null || typeof ir !== 'object' || Array.isArray(ir)) { - return { ir: null, code: 'contract-invalid', error: `${source} is not a JSON IR object.` }; - } - const contract = ir as IrContract; - if (typeof contract.ir_version !== 'string') { - return { - ir: null, - code: 'contract-invalid', - error: `${source} is missing its string ir_version.`, - }; - } - if (contract.ir_version !== TYWRAP_IR_VERSION) { - return { - ir: null, - code: 'ir-version-mismatch', - error: `IR version mismatch: TypeScript expects ${TYWRAP_IR_VERSION}, but ${source} declares ${contract.ir_version}. Regenerate the contract with a matching tywrap_ir.`, - }; - } - if (typeof contract.module !== 'string' || contract.module.length === 0) { - return { ir: null, code: 'contract-invalid', error: `${source} is missing its module name.` }; +): { ir: ValidatedIrContract | null; error?: string; code?: GenerateFailure['code'] } { + const result = validateIrContract(ir, source); + if (result.ok) { + return { ir: result.contract }; } - const requiredArrays: ReadonlyArray = [ - ['functions', contract.functions], - ['classes', contract.classes], - ['type_aliases', contract.type_aliases], - ]; - for (const [field, value] of requiredArrays) { - if (!Array.isArray(value)) { - return { - ir: null, - code: 'contract-invalid', - error: `${source} is missing required array field ${field}.`, - }; - } - } - return { ir: contract }; + const first = result.diagnostics[0]; + return { + ir: null, + code: first?.code ?? 'contract-invalid', + error: first?.message ?? `${source} is not a JSON IR object.`, + }; } async function safeReadFile(path: string): Promise { @@ -172,7 +146,7 @@ async function fetchAndCacheIr( cacheKey: string, caching: boolean, checkMode: boolean -): Promise<{ ir: IrContract | null; error?: string; code?: GenerateFailure['code'] }> { +): Promise<{ ir: ValidatedIrContract | null; error?: string; code?: GenerateFailure['code'] }> { let ir: unknown | null = null; let irError: string | undefined; if (caching && fsUtils.isAvailable() && !checkMode) { @@ -217,7 +191,7 @@ async function fetchAndCacheIr( async function readContractInput( moduleKey: string, contractInput: TywrapOptions['contractInput'] -): Promise<{ ir: IrContract | null; error?: string; code?: GenerateFailure['code'] }> { +): Promise<{ ir: ValidatedIrContract | null; error?: string; code?: GenerateFailure['code'] }> { const inputPath = typeof contractInput === 'string' ? contractInput : contractInput?.[moduleKey]; if (!inputPath) { return { @@ -228,7 +202,17 @@ async function readContractInput( } try { const parsed = JSON.parse(await fsUtils.readFile(inputPath)) as unknown; - const validated = validateIrVersion(parsed, `Contract ${inputPath}`); + const validation = validateIrContract(parsed, `Contract ${inputPath}`, { + allowOmittedMetadata: true, + }); + const validated = validation.ok + ? { ir: validation.contract } + : { + ir: null, + code: validation.diagnostics[0]?.code ?? 'contract-invalid', + error: + validation.diagnostics[0]?.message ?? `Contract ${inputPath} is not a JSON IR object.`, + }; if (!validated.ir) { return { ir: null, error: validated.error, code: validated.code }; } @@ -455,14 +439,70 @@ export async function generate( const irWarnings = Array.isArray((ir as Record).warnings) ? ((ir as Record).warnings as unknown[]) : []; + + const moduleModel = transformIrToTsModel(ir, recordUnknown); + + // Apply module-level export filtering (functions/classes + excludes). + filterModuleExports(moduleModel, moduleConfig, moduleKey, warnings); + + // Resolve callable values once before emitting declarations and wrappers. + const annotatedJSDoc = Boolean(resolvedOptions.output?.annotatedJSDoc); + const compiled = compileContract(ir, { + module: moduleModel, + generator: instance.generator, + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + annotatedJSDoc, + }); + const gen = compiled.generated; + for (const diagnostic of compiled.diagnostics) { + warnings.push(diagnostic.message); + } for (const warning of irWarnings) { if (typeof warning !== 'string') { continue; } - // Only type-honesty degrades feed --fail-on-warn. Environment capability - // notices (e.g. typing.get_overloads missing on Python < 3.11) describe - // the analyzing interpreter, not the generated types, and must not fail - // an otherwise clean build. + const external = warning.match( + /^Return annotation for (.+) resolves outside analyzed module: (.+)\.$/ + ); + if (external) { + const qualname = external[1]; + const candidate = external[2]; + const functionIndex = ir.functions.findIndex(func => func.qualname === qualname); + const classIndex = ir.classes.findIndex(cls => + cls.methods.some(method => method.qualname === qualname) + ); + const methodIndex = + classIndex < 0 + ? -1 + : ir.classes[classIndex]!.methods.findIndex(method => method.qualname === qualname); + const path = + functionIndex >= 0 + ? `$.functions[${functionIndex}]` + : methodIndex >= 0 + ? `$.classes[${classIndex}].methods[${methodIndex}]` + : ''; + const callableResult = compiled.callables.find(callable => callable.path === path)?.result; + const logicalType = callableResult?.logicalType; + const outerName = + logicalType && + (logicalType.kind === 'custom' || logicalType.kind === 'generic') && + logicalType.module + ? `${logicalType.module}.${logicalType.name}` + : undefined; + const resolution = callableResult?.resolution; + if ( + resolution?.status === 'supported' && + candidate === outerName && + ((resolution.value.kind === 'ndarray-float16' && + (candidate === 'numpy.ndarray' || candidate === 'numpy.typing.NDArray')) || + (resolution.value.kind === 'torch-float16' && + (candidate === 'torch.Tensor' || candidate === 'torch.HalfTensor'))) + ) { + continue; + } + } + // Runtime notices do not fail strict mode. Type-honesty warnings do. if (warning.startsWith('Return annotation for ')) { recordUnknown(`Python IR warning: ${warning}`); } else { @@ -470,15 +510,6 @@ export async function generate( } } - const moduleModel = transformIrToTsModel(ir); - - // Apply module-level export filtering (functions/classes + excludes). - filterModuleExports(moduleModel, moduleConfig, moduleKey, warnings); - - // Generate module code - const annotatedJSDoc = Boolean(resolvedOptions.output?.annotatedJSDoc); - const gen = instance.generator.generateModuleDefinition(moduleModel, annotatedJSDoc); - const baseName = moduleModel.name || 'module'; const filesToEmit: Array<{ path: string; content: string }> = [ { path: pathUtils.join(outputDir, `${baseName}.generated.ts`), content: gen.typescript }, @@ -627,197 +658,6 @@ async function fetchPythonIr( } } -/** - * Convert JSON IR from Python into the internal TypeScript model used by the generator. - */ -function collectModuleTypeVarNames(obj: Record): Set { - const names = new Set(); - const constants = Array.isArray(obj.constants) ? (obj.constants as unknown[]) : []; - - for (const constant of constants) { - const entry = constant as Record; - const name = typeof entry.name === 'string' ? entry.name.trim() : ''; - if (!name) { - continue; - } - - const valueRepr = typeof entry.value_repr === 'string' ? entry.value_repr.trim() : ''; - if (/^~?[A-Za-z_][A-Za-z0-9_]*$/.test(valueRepr) && valueRepr.replace(/^~/, '') === name) { - names.add(name); - continue; - } - - const annotation = typeof entry.annotation === 'string' ? entry.annotation.trim() : ''; - if (/(^|\.)(TypeVar|ParamSpec|TypeVarTuple)(\[|\(|$)/.test(annotation)) { - names.add(name); - } - } - - return names; -} - -function transformIrToTsModel(ir: unknown): TSPythonModule { - const obj: Record = - typeof ir === 'object' && ir !== null ? (ir as Record) : {}; - const functions = (obj.functions as unknown[]) ?? []; - const classes = (obj.classes as unknown[]) ?? []; - const aliases = (obj.type_aliases as unknown[]) ?? []; - const moduleTypeVarNames = collectModuleTypeVarNames(obj); - const parseType = ( - annotation: unknown, - typeParameters: readonly PythonGenericParameter[] = [] - ): PythonType => - parseAnnotationToPythonType(annotation, { - onUnknownTypeName: recordUnknown, - knownTypeVarNames: moduleTypeVarNames, - typeParameters, - }); - const mapTypeParameters = (value: Record): PythonGenericParameter[] => - Array.isArray(value.type_params) - ? (value.type_params as unknown[]).map(v => { - const param = (v ?? {}) as Record; - return { - name: String(param.name ?? ''), - kind: String(param.kind ?? 'typevar') as PythonGenericParameter['kind'], - bound: param.bound ? parseType(param.bound) : undefined, - constraints: Array.isArray(param.constraints) - ? (param.constraints as unknown[]).map(item => parseType(item)) - : undefined, - variance: - param.variance === 'covariant' || - param.variance === 'contravariant' || - param.variance === 'invariant' - ? param.variance - : undefined, - } satisfies PythonGenericParameter; - }) - : []; - const mapParam = ( - p: Record, - typeParameters: readonly PythonGenericParameter[] = [] - ): Parameter => ({ - name: String(p.name ?? ''), - type: parseType(p.annotation, typeParameters), - optional: Boolean(p.default), - varArgs: p.kind === 'VAR_POSITIONAL', - kwArgs: p.kind === 'VAR_KEYWORD', - positionalOnly: p.kind === 'POSITIONAL_ONLY', - keywordOnly: p.kind === 'KEYWORD_ONLY', - }); - - const mapMethodKind = (value: unknown): PythonFunction['methodKind'] => - value === 'class' || value === 'static' ? value : 'instance'; - - const mapFunc = ( - f: Record, - inheritedTypeParameters: readonly PythonGenericParameter[] = [] - ): PythonFunction => { - const localTypeParameters = mapTypeParameters(f); - const annotationTypeParameters = [...inheritedTypeParameters, ...localTypeParameters]; - return { - name: String(f.name ?? ''), - signature: { - parameters: Array.isArray(f.parameters) - ? (f.parameters as unknown[]).map(v => - mapParam((v ?? {}) as Record, annotationTypeParameters) - ) - : [], - returnType: parseType(f.returns, annotationTypeParameters), - isAsync: Boolean(f.is_async), - isGenerator: Boolean(f.is_generator), - }, - docstring: (f.docstring as string | undefined) ?? undefined, - decorators: [], - isAsync: Boolean(f.is_async), - isGenerator: Boolean(f.is_generator), - typeParameters: [...localTypeParameters], - returnType: parseType(f.returns, annotationTypeParameters), - parameters: Array.isArray(f.parameters) - ? (f.parameters as unknown[]).map(v => - mapParam((v ?? {}) as Record, annotationTypeParameters) - ) - : [], - methodKind: mapMethodKind(f.method_kind), - }; - }; - - const mapClass = (c: Record): PythonClass => { - const classTypeParameters = mapTypeParameters(c); - return { - name: String(c.name ?? ''), - bases: Array.isArray(c.bases) ? (c.bases as string[]) : [], - methods: Array.isArray(c.methods) - ? (c.methods as unknown[]).map(v => - mapFunc((v ?? {}) as Record, classTypeParameters) - ) - : [], - properties: Array.isArray(c.fields) - ? (c.fields as unknown[]).map(v => { - const p = (v ?? {}) as Record; - return { - name: String(p.name ?? ''), - type: parseType(p.annotation, classTypeParameters), - readonly: false, - setter: false, - getter: true, - optional: Boolean(p.default), - }; - }) - : [], - accessors: Array.isArray(c.accessors) - ? (c.accessors as unknown[]).map(v => { - const a = (v ?? {}) as Record; - return { - name: String(a.name ?? ''), - type: parseType(a.returns, classTypeParameters), - docstring: (a.docstring as string | undefined) ?? undefined, - readOnly: typeof a.read_only === 'boolean' ? a.read_only : undefined, - isCached: Boolean(a.is_cached), - }; - }) - : [], - docstring: (c.docstring as string | undefined) ?? undefined, - decorators: (c.typed_dict as boolean) ? ['__typed_dict__'] : [], - kind: (c.typed_dict as boolean) - ? 'typed_dict' - : (c.is_protocol as boolean) - ? 'protocol' - : (c.is_namedtuple as boolean) - ? 'namedtuple' - : (c.is_dataclass as boolean) - ? 'dataclass' - : (c.is_pydantic as boolean) - ? 'pydantic' - : 'class', - typeParameters: classTypeParameters, - }; - }; - - const mapTypeAlias = (alias: Record): PythonTypeAlias => { - const typeParameters = mapTypeParameters(alias); - return { - name: String(alias.name ?? ''), - type: parseType(alias.definition, typeParameters), - typeParameters, - }; - }; - - const moduleModel: TSPythonModule = { - name: (obj.module as string) ?? 'module', - path: undefined, - version: - typeof (obj.metadata as Record | undefined)?.package_version === 'string' - ? ((obj.metadata as Record | undefined)?.package_version as string) - : undefined, - functions: functions.map(v => mapFunc((v ?? {}) as Record)), - classes: classes.map(v => mapClass((v ?? {}) as Record)), - typeAliases: aliases.map(v => mapTypeAlias((v ?? {}) as Record)), - imports: [], - exports: [], - }; - return moduleModel; -} - /** * Compute a stable cache key filename for a module and options */ diff --git a/src/utils/codec.ts b/src/utils/codec.ts index 19134559..83d26a2b 100644 --- a/src/utils/codec.ts +++ b/src/utils/codec.ts @@ -10,6 +10,8 @@ */ import { tagDecodedShape } from '../runtime/validators.js'; +import type { DecodedProvenance } from '../runtime/decoded-provenance.js'; +import { isSafeJsonInteger, MAX_SAFE_JSON_INTEGER } from '../contracts/value-contract.js'; const SCIENTIFIC_MARKERS = [ 'dataframe', @@ -376,17 +378,20 @@ function isPromiseLike(value: unknown): value is PromiseLike { * @param arr - Typed array or plain array * @returns Plain JavaScript array with values converted (BigInt → Number where safe) */ -function typedArrayToPlain(arr: unknown): unknown[] | null { +function typedArrayToPlain(arr: unknown, dtype?: string): unknown[] | null { if (Array.isArray(arr)) { - return arr; + return dtype === 'float16' ? arr.map(decodeFloat16StorageWord) : arr; } // Handle typed arrays (Int32Array, Float64Array, BigInt64Array, etc.) if (ArrayBuffer.isView(arr) && 'length' in arr) { + if (dtype === 'float16') { + return Array.from(arr as unknown as ArrayLike, decodeFloat16StorageWord); + } const values = Array.from(arr as unknown as ArrayLike); return values.map(value => { // Convert BigInt to Number if within safe integer range if (typeof value === 'bigint') { - if (value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER)) { + if (value >= BigInt(-MAX_SAFE_JSON_INTEGER) && value <= BigInt(MAX_SAFE_JSON_INTEGER)) { return Number(value); } } @@ -395,7 +400,8 @@ function typedArrayToPlain(arr: unknown): unknown[] | null { } // Fallback: check if iterable before converting if (arr !== null && arr !== undefined && typeof arr === 'object' && Symbol.iterator in arr) { - return Array.from(arr as Iterable); + const values = Array.from(arr as Iterable); + return dtype === 'float16' ? values.map(decodeFloat16StorageWord) : values; } return null; } @@ -406,16 +412,30 @@ function typedArrayToPlain(arr: unknown): unknown[] | null { * Why: Arrow decoding returns Table objects, not raw arrays. We need to extract * the column values and convert any typed arrays to plain arrays. */ -function extractArrowValues(data: unknown): unknown[] | null { +function extractArrowValues(data: unknown, dtype?: string): unknown[] | null { if (Array.isArray(data)) { - return data; + return typedArrayToPlain(data, dtype); } // Arrow table - extract values from first column - const table = data as ArrowTable & { getChildAt?: (i: number) => { toArray?: () => unknown } }; + const table = data as ArrowTable & { + getChildAt?: (i: number) => { + toArray?: () => unknown; + type?: unknown; + nullCount?: number; + }; + }; if (typeof table.getChildAt === 'function') { const column = table.getChildAt(0); if (column && typeof column.toArray === 'function') { - return typedArrayToPlain(column.toArray()); + if (dtype === 'float16') { + if (column.type !== undefined && String(column.type) !== 'Float16') { + throw new Error('float16 Arrow column type does not match envelope dtype'); + } + if (column.nullCount !== undefined && column.nullCount > 0) { + throw new Error('float16 Arrow column contains null values'); + } + } + return typedArrayToPlain(column.toArray(), dtype); } } return null; @@ -427,7 +447,7 @@ function extractNdarrayArrowValues( dtype: string | undefined ): unknown[] { try { - const values = extractArrowValues(data); + const values = extractArrowValues(data, dtype); if (values) { return values; } @@ -646,6 +666,31 @@ function assertArrowCount( } } +/** Decode one IEEE 754 binary16 storage word. Keep negative zero. */ +function float16StorageToNumber(bits: number): number { + const sign = bits & 0x8000 ? -1 : 1; + const exponent = (bits >>> 10) & 0x1f; + const fraction = bits & 0x03ff; + if (exponent === 0) { + return sign * fraction * 2 ** -24; + } + if (exponent === 0x1f) { + return fraction === 0 ? sign * Infinity : NaN; + } + return sign * (1024 + fraction) * 2 ** (exponent - 25); +} + +function decodeFloat16StorageWord(bits: unknown, index: number): number { + if (typeof bits !== 'number' || !isSafeJsonInteger(bits) || bits < 0 || bits > 0xffff) { + throw new Error(`Invalid ndarray envelope: float16 storage at b64[${index}] must be a uint16`); + } + const number = float16StorageToNumber(bits); + if (!Number.isFinite(number)) { + throw new Error(`Invalid ndarray envelope: non-finite float16 value at b64[${index}]`); + } + return number; +} + function assertCodecVersion(envelope: { codecVersion?: unknown }, typeTag: string): void { if (!('codecVersion' in envelope)) { return; @@ -723,7 +768,7 @@ function finishNdarrayDecode( ): unknown { const values = strictV1 ? extractNdarrayArrowValues(data, shape, dtype) - : extractArrowValues(data); + : extractArrowValues(data, dtype); if (!values) { return tagDecodedShape(data, metadata); } @@ -1064,6 +1109,19 @@ const decodeTorchTensorEnvelope: EnvelopeHandler = ( if (strictV1 && 'dtype' in nested) { assertOptionalNonEmptyDtype(nested.dtype, 'torch.tensor', 'value.dtype', nestedShape); } + if (strictV1 && dtype === 'torch.float16') { + if (!isStrictV1Envelope(nested)) { + throw new Error( + 'Invalid torch.tensor envelope: float16 value must use ndarray codecVersion 1' + ); + } + if (nested.dtype !== 'float16') { + throw new Error( + `Invalid torch.tensor envelope: value.dtype at path value.dtype must be "float16" ` + + `for outer dtype "torch.float16"; got ${JSON.stringify(nested.dtype)}` + ); + } + } const deviceValue = value.device; if (deviceValue !== undefined && (typeof deviceValue !== 'string' || deviceValue.length === 0)) { throw new Error( @@ -1290,7 +1348,8 @@ function decodeEnvelope( async function decodeEnvelopeAsync( value: unknown, - decodeArrow: (bytes: Uint8Array, marker: ScientificMarker) => Promise + decodeArrow: (bytes: Uint8Array, marker: ScientificMarker) => Promise, + provenance?: DecodedProvenance ): Promise { let visitedNodes = 0; @@ -1353,6 +1412,34 @@ async function decodeEnvelopeAsync( } }; + const recordScalarProvenance = ( + original: unknown, + decoded: unknown, + target?: DecodeTarget + ): void => { + if ( + !provenance || + typeof decoded !== 'number' || + !isPlainObject(original) || + original.__tywrap__ !== 'ndarray' || + !isStrictV1Envelope(original) || + !Array.isArray(original.shape) || + original.shape.length !== 0 + ) { + return; + } + const metadata = { + marker: 'ndarray' as const, + dims: 0, + dtype: typeof original.dtype === 'string' ? original.dtype : undefined, + }; + if (target) { + provenance.recordChild(target.container, target.key, metadata); + } else { + provenance.recordRoot(metadata); + } + }; + const settleDecoded = async ( decoded: PromiseLike, original: unknown, @@ -1365,6 +1452,7 @@ async function decodeEnvelopeAsync( } catch (error) { return prefixHandlerError(error, path); } + recordScalarProvenance(original, resolved, path === 'result' ? undefined : target); assignDecoded(target, original, resolved); }; @@ -1411,8 +1499,10 @@ async function decodeEnvelopeAsync( pending.push(settleDecoded(decoded, current, { container: root, key: 'value' }, path)); } } else if (target) { + recordScalarProvenance(current, decoded, target); assignDecoded(target, current, decoded); } else if (decoded !== current) { + recordScalarProvenance(current, decoded); root.value = decoded; } return; @@ -1486,9 +1576,12 @@ async function decodeEnvelopeAsync( /** * Decode values produced by the Python bridge. */ -export async function decodeValueAsync(value: unknown): Promise { +export async function decodeValueAsync( + value: unknown, + provenance?: DecodedProvenance +): Promise { try { - return await decodeEnvelopeAsync(value, tryDecodeArrowTable); + return await decodeEnvelopeAsync(value, tryDecodeArrowTable, provenance); } catch (error) { throw asScientificDecodeError(error, 'unknown'); } diff --git a/test/annotation-parser.test.ts b/test/annotation-parser.test.ts index 9d87863e..f4fb0c99 100644 --- a/test/annotation-parser.test.ts +++ b/test/annotation-parser.test.ts @@ -68,4 +68,35 @@ describe('annotation parser', () => { expect((t as any).name).toBe('args'); expect((t as any).module).toBe('Request'); }); + + it('keeps NumPy dtype detail without warning on its shape wildcard', () => { + const unknown: string[] = []; + const type = parseAnnotationToPythonType( + 'numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[numpy.float16]]', + { onUnknownTypeName: name => unknown.push(name) } + ); + expect(type).toMatchObject({ + kind: 'generic', + name: 'ndarray', + module: 'numpy', + typeArgs: [ + { kind: 'collection', name: 'tuple' }, + { + kind: 'generic', + name: 'dtype', + module: 'numpy', + typeArgs: [{ kind: 'custom', name: 'float16', module: 'numpy' }], + }, + ], + }); + expect(unknown).toEqual([]); + parseAnnotationToPythonType('numpy.ndarray[tuple[Any, ...], numpy.dtype[numpy.float16]]', { + onUnknownTypeName: name => unknown.push(name), + }); + expect(unknown).toEqual([]); + parseAnnotationToPythonType('list[Any]', { + onUnknownTypeName: name => unknown.push(name), + }); + expect(unknown).toEqual(['Any']); + }); }); diff --git a/test/architecture_mutations.test.ts b/test/architecture_mutations.test.ts new file mode 100644 index 00000000..d180f7c7 --- /dev/null +++ b/test/architecture_mutations.test.ts @@ -0,0 +1,196 @@ +import { describe, expect, it } from 'vitest'; + +import { + compileContract, + DEFAULT_CALLABLE_CAPABILITIES, + DEFAULT_VALUE_CONVERSION, + type CapabilityDescription, +} from '../src/core/callable-compiler.js'; +import { CodeGenerator } from '../src/core/generator.js'; +import { validateIrContract } from '../src/core/ir-contract.js'; +import { BridgeCodec } from '../src/runtime/bridge-codec.js'; +import { BridgeCodecError } from '../src/runtime/errors.js'; +import type { PythonModule, PythonType } from '../src/types/index.js'; + +function tensorEnvelope(): Record { + return { + __tywrap__: 'torch.tensor', + codecVersion: 1, + encoding: 'ndarray', + dtype: 'torch.float16', + shape: [2], + device: 'cpu', + value: { + __tywrap__: 'ndarray', + codecVersion: 1, + encoding: 'json', + dtype: 'float16', + shape: [2], + data: [1.5, -2.25], + }, + }; +} + +async function decode(result: unknown): Promise { + return new BridgeCodec().decodeResponseAsync( + JSON.stringify({ id: 1, protocol: 'tywrap/1', result }) + ); +} + +async function expectDecodeFailure(result: unknown, marker: string): Promise { + let caught: unknown; + try { + await decode(result); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(BridgeCodecError); + expect(caught).toMatchObject({ codecPhase: 'decode', valueType: marker }); +} + +function compileReturn( + returnType: PythonType, + annotation: string, + capabilities: readonly CapabilityDescription[] = DEFAULT_CALLABLE_CAPABILITIES +) { + const rawIr = { + ir_version: '0.4.0', + module: 'mutation_fixture', + functions: [ + { + name: 'probe', + qualname: 'mutation_fixture.probe', + docstring: null, + parameters: [], + returns: annotation, + is_async: false, + is_generator: false, + type_params: [], + method_kind: 'instance', + overloads: [], + }, + ], + classes: [], + constants: [], + type_aliases: [], + metadata: {}, + warnings: [], + }; + const validation = validateIrContract(rawIr, 'mutation fixture'); + if (!validation.ok) { + throw new Error(`Mutation fixture did not validate: ${JSON.stringify(validation.diagnostics)}`); + } + const module: PythonModule = { + name: 'mutation_fixture', + functions: [ + { + name: 'probe', + signature: { parameters: [], returnType, isAsync: false, isGenerator: false }, + decorators: [], + isAsync: false, + isGenerator: false, + parameters: [], + returnType, + }, + ], + classes: [], + imports: [], + exports: [], + }; + return compileContract(validation.contract, { + module, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities, + }); +} + +describe('architecture contract mutations', () => { + it('accepts the matching strict v1 Torch envelope', async () => { + await expect(decode(tensorEnvelope())).resolves.toMatchObject({ + data: [1.5, -2.25], + shape: [2], + dtype: 'torch.float16', + device: 'cpu', + }); + }); + + it('rejects an outer Torch float16 dtype paired with nested float32', async () => { + const envelope = tensorEnvelope(); + envelope.value = { ...(envelope.value as object), dtype: 'float32' }; + await expectDecodeFailure(envelope, 'torch.tensor'); + }); + + it.each([ + { + name: 'outer shape', + mutate: (envelope: Record) => { + envelope.shape = [1, 2]; + }, + }, + { + name: 'codec version', + mutate: (envelope: Record) => { + envelope.codecVersion = 2; + }, + }, + { + name: 'encoding', + mutate: (envelope: Record) => { + envelope.encoding = 'raw'; + }, + }, + ])('rejects a mutated $name with a structured decode error', async ({ mutate }) => { + const envelope = tensorEnvelope(); + mutate(envelope); + await expectDecodeFailure(envelope, 'torch.tensor'); + }); + + it('reports an unsupported record key conversion at the return path', () => { + const compiled = compileReturn( + { + kind: 'collection', + name: 'dict', + itemTypes: [ + { kind: 'primitive', name: 'int' }, + { kind: 'primitive', name: 'str' }, + ], + }, + 'dict[int, str]' + ); + expect(compiled.diagnostics).toContainEqual( + expect.objectContaining({ + severity: 'error', + code: 'conversion-unsupported', + path: '$.functions[0].returns', + }) + ); + expect(compiled.callables[0]?.result.resolution.status).toBe('unsupported'); + expect(compiled.module.functions[0]?.callableContract?.returnValue).toBeUndefined(); + }); + + it('reports an unavailable scientific capability at the return path', () => { + const capabilities = DEFAULT_CALLABLE_CAPABILITIES.map(capability => + capability.name === 'scientific-ndarray' ? { ...capability, available: false } : capability + ); + const compiled = compileReturn( + { + kind: 'generic', + name: 'NDArray', + module: 'numpy.typing', + typeArgs: [{ kind: 'custom', name: 'float16', module: 'numpy' }], + }, + 'numpy.typing.NDArray[numpy.float16]', + capabilities + ); + expect(compiled.diagnostics).toContainEqual( + expect.objectContaining({ + severity: 'error', + code: 'capability-unavailable', + path: '$.functions[0].returns', + }) + ); + expect(compiled.callables[0]?.result.resolution.status).toBe('unsupported'); + expect(compiled.module.functions[0]?.callableContract?.returnValue).toBeUndefined(); + }); +}); diff --git a/test/architecture_numeric_oracle.test.ts b/test/architecture_numeric_oracle.test.ts new file mode 100644 index 00000000..fcded9fa --- /dev/null +++ b/test/architecture_numeric_oracle.test.ts @@ -0,0 +1,246 @@ +import { execFile } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +import * as arrow from 'apache-arrow'; +import * as fc from 'fast-check'; +import { afterEach, beforeAll, describe, expect, it } from 'vitest'; + +import { VALUE_CONTRACT_REVISION, isSafeJsonInteger } from '../src/contracts/value-contract.js'; +import { + clearArrowDecoder, + decodeValue, + decodeValueAsync, + registerArrowDecoder, + type ArrowTable, +} from '../src/utils/codec.js'; + +const fixturePath = fileURLToPath( + new URL('./fixtures/architecture-value-cases.v1.json', import.meta.url) +); +const oraclePath = fileURLToPath( + new URL('./python/architecture_numeric_oracle.py', import.meta.url) +); +const python = process.env.PYTHON ?? (process.platform === 'win32' ? 'python' : 'python3'); +const execFileAsync = promisify(execFile); + +interface FixedCase { + wordHex: string; + decimal: string; + negativeZero: boolean; +} + +interface ArchitectureFixture { + schemaVersion: number; + contractRevision: number; + propertySeed: number; + safeIntegers: Array<{ decimal: string; accepted: boolean }>; + binary16: FixedCase[]; + nonFiniteBinary16: Array<{ wordHex: string; kind: 'infinity' | 'nan' }>; + nestedCases: Array<{ path: string; float16Words?: string[] }>; +} + +interface NumericOracle { + contractRevision: number; + method: string; + words: Array<[decimalOrKind: string, negativeZero: boolean]>; + integers: Array<{ decimal: string; accepted: boolean }>; +} + +const fixture = JSON.parse(readFileSync(fixturePath, 'utf8')) as ArchitectureFixture; +const lockfile = JSON.parse( + readFileSync(new URL('../package-lock.json', import.meta.url), 'utf8') +) as { packages: Record }; +let oracle: NumericOracle; + +function isNonFinite(label: string): boolean { + return label === 'NaN' || label === '+Infinity' || label === '-Infinity'; +} + +function decimalFor(word: number): number { + const entry = oracle.words[word]; + if (!entry || isNonFinite(entry[0])) { + throw new Error(`Expected a finite Python oracle value for word 0x${word.toString(16)}`); + } + return Number(entry[0]); +} + +function envelope(shape: number[], b64 = 'AA=='): object { + return { + __tywrap__: 'ndarray', + codecVersion: 1, + encoding: 'arrow', + b64, + shape, + dtype: 'float16', + }; +} + +function registerStorageWords(words: readonly number[]): void { + registerArrowDecoder( + () => + ({ + getChildAt: () => ({ + type: 'Float16', + nullCount: 0, + toArray: () => Uint16Array.from(words), + }), + }) as ArrowTable + ); +} + +beforeAll(async () => { + const { stdout } = await execFileAsync(python, [oraclePath, fixturePath], { + timeout: 20_000, + maxBuffer: 4 * 1024 * 1024, + env: { ...process.env, PYTHONNOUSERSITE: '1' }, + }); + oracle = JSON.parse(stdout) as NumericOracle; + expect(fixture.schemaVersion).toBe(1); + expect(fixture.contractRevision).toBe(VALUE_CONTRACT_REVISION); + expect(oracle.contractRevision).toBe(VALUE_CONTRACT_REVISION); + expect(oracle.method).toBe('python-stdlib-struct-unpack-binary16'); + expect(lockfile.packages['node_modules/apache-arrow']?.version).toBe('21.1.0'); + expect(oracle.words).toHaveLength(0x10000); + expect(oracle.integers).toHaveLength(fixture.safeIntegers.length); +}, 30_000); + +afterEach(() => clearArrowDecoder()); + +describe('architecture numeric oracle', () => { + it('agrees with Python on the fixed safe-integer domain', () => { + for (const [index, fixed] of fixture.safeIntegers.entries()) { + expect(oracle.integers[index]).toEqual(fixed); + const asNumber = Number(fixed.decimal); + expect(isSafeJsonInteger(asNumber), fixed.decimal).toBe(fixed.accepted); + if (fixed.accepted) { + expect(BigInt(asNumber)).toBe(BigInt(fixed.decimal)); + } + } + }); + + it('matches every finite binary16 word against Python struct.unpack', () => { + const words: number[] = []; + const expected: number[] = []; + let nonFiniteCount = 0; + for (let word = 0; word < oracle.words.length; word += 1) { + const entry = oracle.words[word]; + if (!entry) { + throw new Error(`Python oracle omitted word ${word}`); + } + if (isNonFinite(entry[0])) { + nonFiniteCount += 1; + if (entry[1]) { + throw new Error(`Non-finite word 0x${word.toString(16)} has a zero flag`); + } + continue; + } + const value = Number(entry[0]); + if (!Number.isFinite(value)) { + throw new Error(`Python oracle word 0x${word.toString(16)} is not finite`); + } + if (Object.is(value, -0) !== entry[1]) { + throw new Error(`Python oracle word 0x${word.toString(16)} has the wrong zero flag`); + } + words.push(word); + expected.push(value); + } + expect(words).toHaveLength(63_488); + expect(nonFiniteCount).toBe(2_048); + + // This injects Arrow storage words. The clean consumer test covers real Python Arrow output. + registerStorageWords(words); + const decoded = decodeValue(envelope([words.length])) as number[]; + expect(decoded).toHaveLength(words.length); + for (let index = 0; index < words.length; index += 1) { + if (!Object.is(decoded[index], expected[index])) { + throw new Error(`binary16 word 0x${words[index]?.toString(16)} differs from Python`); + } + } + }, 30_000); + + it('matches fixed finite cases and rejects NaN and infinity', () => { + for (const fixed of fixture.binary16) { + const word = Number.parseInt(fixed.wordHex, 16); + const expected = Number(fixed.decimal); + expect(Object.is(decimalFor(word), expected), fixed.wordHex).toBe(true); + expect(oracle.words[word]?.[1], fixed.wordHex).toBe(fixed.negativeZero); + registerStorageWords([word]); + const decoded = decodeValue(envelope([1])) as number[]; + expect(Object.is(decoded[0], expected), fixed.wordHex).toBe(true); + } + for (const fixed of fixture.nonFiniteBinary16) { + const word = Number.parseInt(fixed.wordHex, 16); + const label = oracle.words[word]?.[0]; + expect(fixed.kind === 'nan' ? label === 'NaN' : label?.endsWith('Infinity')).toBe(true); + registerStorageWords([word]); + expect(() => decodeValue(envelope([1]))).toThrow(/non-finite float16/); + } + }); + + it('decodes scalar and multidimensional shapes through real Arrow IPC', () => { + const words = Uint16Array.of(0x3e00, 0xc080, 0x0001, 0x8000); + const vector = arrow.makeVector({ type: new arrow.Float16(), data: words }); + const table = arrow.tableFromArrays({ value: vector }); + const b64 = Buffer.from(arrow.tableToIPC(table, 'stream')).toString('base64'); + registerArrowDecoder(bytes => arrow.tableFromIPC(bytes) as unknown as ArrowTable); + + const decoded = decodeValue(envelope([2, 2], b64)) as number[][]; + expect(decoded).toHaveLength(2); + expect(decoded[0]).toEqual([decimalFor(0x3e00), decimalFor(0xc080)]); + expect(decoded[1]?.[0]).toBe(decimalFor(0x0001)); + expect(Object.is(decoded[1]?.[1], -0)).toBe(true); + + const scalar = arrow.tableFromArrays({ + value: arrow.makeVector({ type: new arrow.Float16(), data: Uint16Array.of(0x3e00) }), + }); + const scalarB64 = Buffer.from(arrow.tableToIPC(scalar, 'stream')).toString('base64'); + expect(decodeValue(envelope([], scalarB64))).toBe(decimalFor(0x3e00)); + }); + + it('reuses float16 conversion inside Torch and records with a retained seed', async () => { + const nested = fixture.nestedCases.find(testCase => testCase.float16Words); + if (!nested?.float16Words) { + throw new Error('Missing nested Torch fixture'); + } + expect(nested.path).toBe('result.outer[0].tensor.value'); + const fixedWords = nested.float16Words.map(word => Number.parseInt(word, 16)); + + const finiteWord = fc.integer({ min: 0, max: 0xffff }).filter(word => { + const entry = oracle.words[word]; + return entry !== undefined && !isNonFinite(entry[0]); + }); + await fc.assert( + fc.asyncProperty(fc.array(finiteWord, { minLength: 1, maxLength: 8 }), async sampledWords => { + const words = [...fixedWords, ...sampledWords]; + registerStorageWords(words); + const decoded = (await decodeValueAsync({ + outer: [ + { + tensor: { + __tywrap__: 'torch.tensor', + codecVersion: 1, + encoding: 'ndarray', + value: envelope([words.length]), + shape: [words.length], + dtype: 'torch.float16', + device: 'cpu', + }, + }, + ], + })) as { outer: Array<{ tensor: { data: number[] } }> }; + const values = decoded.outer[0]?.tensor.data; + if (!values || values.length !== words.length) { + throw new Error('Nested Torch value did not keep its shape'); + } + for (let index = 0; index < words.length; index += 1) { + if (!Object.is(values[index], decimalFor(words[index] as number))) { + throw new Error(`Nested float16 word 0x${words[index]?.toString(16)} differs`); + } + } + }), + { seed: fixture.propertySeed, numRuns: 64, verbose: true } + ); + }, 30_000); +}); diff --git a/test/bridge-codec.test.ts b/test/bridge-codec.test.ts index fe83668f..fd38e01a 100644 --- a/test/bridge-codec.test.ts +++ b/test/bridge-codec.test.ts @@ -7,6 +7,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { BridgeCodec, type CodecOptions } from '../src/runtime/bridge-codec.js'; +import { DecodedProvenance } from '../src/runtime/decoded-provenance.js'; import { BridgeCodecError, BridgeProtocolError, @@ -633,6 +634,71 @@ describe('decodeResponseAsync - Arrow Integration', () => { }); }); + it('records scalar ndarray proof at the root and nested array and record slots', async () => { + const scalar = { + __tywrap__: 'ndarray', + codecVersion: 1, + encoding: 'json', + data: 1.5, + shape: [], + dtype: 'float16', + }; + const rootProof = new DecodedProvenance(); + expect( + await codec.decodeResponseAsync( + JSON.stringify({ id: 1, protocol: 'tywrap/1', result: scalar }), + rootProof + ) + ).toBe(1.5); + expect(rootProof.atRoot()).toEqual({ marker: 'ndarray', dims: 0, dtype: 'float16' }); + + const nestedProof = new DecodedProvenance(); + const decoded = await codec.decodeResponseAsync<{ tuple: [number, { value: number }] }>( + JSON.stringify({ + id: 1, + protocol: 'tywrap/1', + result: { tuple: [scalar, { value: scalar }] }, + }), + nestedProof + ); + expect(decoded).toEqual({ tuple: [1.5, { value: 1.5 }] }); + expect(nestedProof.atRoot()).toBeUndefined(); + expect(nestedProof.atChild(decoded.tuple, '0')?.dtype).toBe('float16'); + expect(nestedProof.atChild(decoded.tuple[1], 'value')?.dtype).toBe('float16'); + expect(nestedProof.atChild(decoded.tuple, 1)).toBeUndefined(); + }); + + it('does not record proof for plain numbers or malformed scalar envelopes', async () => { + const plainProof = new DecodedProvenance(); + expect( + await codec.decodeResponseAsync( + JSON.stringify({ id: 1, protocol: 'tywrap/1', result: 1.5 }), + plainProof + ) + ).toBe(1.5); + expect(plainProof.atRoot()).toBeUndefined(); + + const malformedProof = new DecodedProvenance(); + await expect( + codec.decodeResponseAsync( + JSON.stringify({ + id: 1, + protocol: 'tywrap/1', + result: { + __tywrap__: 'ndarray', + codecVersion: 1, + encoding: 'json', + data: 1.5, + shape: [1], + dtype: 'float16', + }, + }), + malformedProof + ) + ).rejects.toThrow(/must be an array at depth 0/); + expect(malformedProof.atRoot()).toBeUndefined(); + }); + it('labels v1 scientific-envelope validation failures without Arrow wording', async () => { const payload = JSON.stringify({ id: 1, diff --git a/test/callable-compiler.test.ts b/test/callable-compiler.test.ts new file mode 100644 index 00000000..71a8c243 --- /dev/null +++ b/test/callable-compiler.test.ts @@ -0,0 +1,2377 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import ts from 'typescript'; +import { + compileContract, + DEFAULT_CALLABLE_CAPABILITIES, + DEFAULT_VALUE_CONVERSION, + EXACT_INTEGER_VALUE_CONVERSION, +} from '../src/core/callable-compiler.js'; +import { CodeGenerator } from '../src/core/generator.js'; +import { parseAnnotationToPythonType } from '../src/core/annotation-parser.js'; +import { validateIrContract } from '../src/core/ir-contract.js'; +import { BridgeValidationError } from '../src/runtime/errors.js'; +import { BridgeCodec } from '../src/runtime/bridge-codec.js'; +import { HttpBridge } from '../src/runtime/http.js'; +import { clearRuntimeBridge, setRuntimeBridge } from 'tywrap/runtime'; +import type { PythonModule, PythonType } from '../src/types/index.js'; + +const rawIr = { + ir_version: '0.4.0', + module: 'fixture', + functions: [ + { + name: 'select', + qualname: 'fixture.select', + docstring: null, + parameters: [ + { name: 'key', kind: 'POSITIONAL_OR_KEYWORD', annotation: 'str | int', default: false }, + ], + returns: 'str | int', + is_async: false, + is_generator: false, + type_params: [], + method_kind: 'instance', + overloads: [ + { + parameters: [ + { name: 'key', kind: 'POSITIONAL_OR_KEYWORD', annotation: 'str', default: false }, + ], + returns: 'str', + }, + { + parameters: [ + { name: 'key', kind: 'POSITIONAL_OR_KEYWORD', annotation: 'int', default: false }, + ], + returns: 'int', + }, + ], + }, + { + name: 'nested', + qualname: 'fixture.nested', + docstring: null, + parameters: [], + returns: 'dict[str, dict[str, int]]', + is_async: false, + is_generator: false, + type_params: [], + method_kind: 'instance', + overloads: [], + }, + { + name: 'async_value', + qualname: 'fixture.async_value', + docstring: null, + parameters: [], + returns: 'str', + is_async: true, + is_generator: false, + type_params: [], + method_kind: 'instance', + overloads: [], + }, + { + name: 'point', + qualname: 'fixture.point', + docstring: null, + parameters: [], + returns: 'fixture.Point', + is_async: false, + is_generator: false, + type_params: [], + method_kind: 'instance', + overloads: [], + }, + ], + classes: [ + { + name: 'Point', + qualname: 'fixture.Point', + docstring: null, + bases: ['object'], + methods: [], + typed_dict: false, + total: null, + fields: [ + { name: 'x', kind: 'FIELD', annotation: 'int', default: false }, + { name: 'y', kind: 'FIELD', annotation: 'int', default: false }, + ], + is_protocol: false, + is_namedtuple: false, + is_dataclass: true, + is_pydantic: false, + type_params: [], + accessors: [], + }, + ], + constants: [], + type_aliases: [], + metadata: {}, + warnings: [], +}; + +const moduleModel: PythonModule = { + name: 'fixture', + functions: [ + { + name: 'select', + signature: { + parameters: [], + returnType: { kind: 'custom', name: 'Any' }, + isAsync: false, + isGenerator: false, + }, + decorators: [], + isAsync: false, + isGenerator: false, + parameters: [ + { + name: 'key', + type: { + kind: 'union', + types: [ + { kind: 'primitive', name: 'str' }, + { kind: 'primitive', name: 'int' }, + ], + }, + optional: false, + varArgs: false, + kwArgs: false, + }, + ], + returnType: { + kind: 'union', + types: [ + { kind: 'primitive', name: 'str' }, + { kind: 'primitive', name: 'int' }, + ], + }, + overloads: [ + { + parameters: [ + { + name: 'key', + type: { kind: 'primitive', name: 'str' }, + optional: false, + varArgs: false, + kwArgs: false, + }, + ], + returnType: { kind: 'primitive', name: 'str' }, + }, + { + parameters: [ + { + name: 'key', + type: { kind: 'primitive', name: 'int' }, + optional: false, + varArgs: false, + kwArgs: false, + }, + ], + returnType: { kind: 'primitive', name: 'int' }, + }, + ], + }, + { + name: 'nested', + signature: { + parameters: [], + returnType: { kind: 'custom', name: 'Any' }, + isAsync: false, + isGenerator: false, + }, + decorators: [], + isAsync: false, + isGenerator: false, + parameters: [], + returnType: { + kind: 'collection', + name: 'dict', + itemTypes: [ + { kind: 'primitive', name: 'str' }, + { + kind: 'collection', + name: 'dict', + itemTypes: [ + { kind: 'primitive', name: 'str' }, + { kind: 'primitive', name: 'int' }, + ], + }, + ], + }, + }, + { + name: 'async_value', + signature: { + parameters: [], + returnType: { kind: 'primitive', name: 'str' }, + isAsync: true, + isGenerator: false, + }, + decorators: [], + isAsync: true, + isGenerator: false, + parameters: [], + returnType: { kind: 'primitive', name: 'str' }, + }, + { + name: 'point', + signature: { + parameters: [], + returnType: { kind: 'custom', name: 'Point' }, + isAsync: false, + isGenerator: false, + }, + decorators: [], + isAsync: false, + isGenerator: false, + parameters: [], + returnType: { kind: 'custom', name: 'Point' }, + }, + ], + classes: [ + { + name: 'Point', + bases: [], + methods: [], + properties: [], + decorators: [], + kind: 'dataclass', + }, + ], + typeAliases: [], + imports: [], + exports: [], +}; + +describe('compileContract', () => { + it('resolves overloads and nested records once before emitting both wrapper files', () => { + const validation = validateIrContract(rawIr, 'fixture contract'); + expect(validation.ok).toBe(true); + if (!validation.ok) { + return; + } + + const compiled = compileContract(validation.contract, { + module: moduleModel, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + + expect(compiled.files.map(file => file.kind)).toEqual(['typescript', 'declaration']); + expect(compiled.generated.typescript).toContain( + 'export function select(key: string): Promise;' + ); + expect(compiled.generated.declaration).toContain( + 'export function select(key: number): Promise;' + ); + expect(compiled.generated.typescript).toContain( + 'export async function select(key: unknown): Promise' + ); + const nested = compiled.callables.find(callable => callable.name === 'nested'); + expect(nested?.result.resolution).toMatchObject({ + status: 'supported', + value: { + kind: 'record', + additionalValues: { + kind: 'record', + additionalValues: { kind: 'integer', constraint: 'safe-integer' }, + }, + }, + }); + const selected = compiled.callables.find(callable => callable.name === 'select'); + expect(selected?.result.resolution).toMatchObject({ + status: 'supported', + value: { + kind: 'union', + options: [ + { kind: 'string', wire: 'json', decodedAs: 'string' }, + { kind: 'integer', wire: 'json', decodedAs: 'number', constraint: 'safe-integer' }, + ], + }, + }); + expect(compiled.generated.typescript).toContain('selectOverloadReturnValidator('); + expect(compiled.generated.typescript).toContain('"constraint":"safe-integer"'); + }); + + it('rejects a wrong return from the generated wrapper for a selected overload', async () => { + const validation = validateIrContract(rawIr, 'fixture contract'); + expect(validation.ok).toBe(true); + if (!validation.ok) { + return; + } + const compiled = compileContract(validation.contract, { + module: moduleModel, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + const temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-overload-')); + try { + const outputPath = join(temporary, 'fixture.generated.mjs'); + const javascript = ts.transpileModule(compiled.generated.typescript, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(outputPath, javascript, 'utf8'); + setRuntimeBridge({ + async call( + _module: string, + _functionName: string, + args: unknown[], + _kwargs?: Record, + validate?: (result: T) => void + ): Promise { + const result = (typeof args[0] === 'string' ? 99 : 4) as T; + validate?.(result); + return result; + }, + async dispose(): Promise {}, + }); + const generated = (await import(pathToFileURL(outputPath).href)) as { + select: (key: string | number) => Promise; + }; + await expect(generated.select('key')).rejects.toThrow(BridgeValidationError); + await expect(generated.select(2)).resolves.toBe(4); + } finally { + clearRuntimeBridge(); + await rm(temporary, { recursive: true, force: true }); + } + }); + + it('warns when an optional parameter makes two overload inputs overlap', () => { + const source = rawIr.functions[0]!; + const key = source.overloads[0]!.parameters[0]!; + const optionalBase = { + name: 'base', + kind: 'POSITIONAL_OR_KEYWORD', + annotation: 'int', + default: true, + }; + const ir = validateIrContract( + { + ...rawIr, + functions: [ + { + ...source, + parameters: [key, optionalBase], + overloads: [ + { parameters: [key], returns: 'str' }, + { parameters: [key, optionalBase], returns: 'int' }, + ], + }, + ], + classes: [], + }, + 'optional overload contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const original = moduleModel.functions[0]!; + const keyModel = original.overloads![0]!.parameters[0]!; + const baseModel = { + ...keyModel, + name: 'base', + type: { kind: 'primitive', name: 'int' } as PythonType, + optional: true, + }; + const model: PythonModule = { + ...moduleModel, + classes: [], + functions: [ + { + ...original, + parameters: [keyModel, baseModel], + overloads: [ + { parameters: [keyModel], returnType: { kind: 'primitive', name: 'str' } }, + { parameters: [keyModel, baseModel], returnType: { kind: 'primitive', name: 'int' } }, + ], + }, + ], + }; + const compiled = compileContract(ir.contract, { + module: model, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: 'overload-ambiguous', + path: '$.functions[0].overloads[1]', + }), + ]) + ); + }); + + it('warns when keyword-only overloads overlap despite declaration order', () => { + const source = rawIr.functions[0]!; + const x = { name: 'x', kind: 'KEYWORD_ONLY', annotation: 'str', default: false }; + const y = { name: 'y', kind: 'KEYWORD_ONLY', annotation: 'int', default: false }; + const ir = validateIrContract( + { + ...rawIr, + functions: [ + { + ...source, + name: 'choose', + qualname: 'fixture.choose', + parameters: [x, y], + overloads: [ + { parameters: [x, y], returns: 'str' }, + { parameters: [y, x], returns: 'int' }, + ], + }, + ], + classes: [], + }, + 'keyword overload contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const compiled = compileContract(ir.contract, { + module: { + ...moduleModel, + functions: [{ ...moduleModel.functions[0]!, name: 'choose' }], + classes: [], + }, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: 'overload-ambiguous', + path: '$.functions[0].overloads[1]', + }), + ]) + ); + }); + + it('takes callable types from validated IR, not from the export selection model', () => { + const source = rawIr.functions[1]!; + const ir = validateIrContract( + { + ...rawIr, + functions: [ + { + ...source, + name: 'echo', + qualname: 'fixture.echo', + parameters: [ + { name: 'value', kind: 'POSITIONAL_OR_KEYWORD', annotation: 'str', default: false }, + ], + returns: 'str', + }, + ], + classes: [], + }, + 'IR authority contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const forged = { + ...moduleModel.functions[1]!, + name: 'echo', + parameters: [ + { + name: 'value', + type: { kind: 'primitive', name: 'int' } as PythonType, + optional: false, + varArgs: false, + kwArgs: false, + }, + ], + returnType: { kind: 'primitive', name: 'int' } as PythonType, + }; + const compiled = compileContract(ir.contract, { + module: { ...moduleModel, functions: [forged], classes: [] }, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.module.functions[0]?.parameters[0]?.type).toEqual({ + kind: 'primitive', + name: 'str', + }); + expect(compiled.callables[0]?.result.resolution).toMatchObject({ + status: 'supported', + value: { kind: 'string' }, + }); + expect(compiled.generated.declaration).toContain('echo(value: string): Promise'); + expect(compiled.generated.declaration).not.toContain('echo(value: number)'); + }); + + it('selects a class method overload without validating its implicit cls receiver', async () => { + const source = rawIr.functions[0]!; + const receiver = { + name: 'cls', + kind: 'POSITIONAL_OR_KEYWORD', + annotation: null, + default: false, + }; + const stringInput = source.overloads[0]!.parameters[0]!; + const integerInput = source.overloads[1]!.parameters[0]!; + const methodIr = { + ...source, + name: 'convert', + qualname: 'fixture.Converter.convert', + parameters: [receiver, source.parameters[0]!], + method_kind: 'class', + overloads: [ + { parameters: [receiver, stringInput], returns: 'str' }, + { parameters: [receiver, integerInput], returns: 'int' }, + ], + }; + const ir = validateIrContract( + { + ...rawIr, + functions: [], + classes: [ + { + ...rawIr.classes[0]!, + name: 'Converter', + qualname: 'fixture.Converter', + methods: [methodIr], + fields: [], + is_dataclass: false, + }, + ], + }, + 'class overload contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const original = moduleModel.functions[0]!; + const receiverModel = { + ...original.parameters[0]!, + name: 'cls', + type: { kind: 'custom', name: 'Any', module: 'typing' } as PythonType, + }; + const method = { + ...original, + name: 'convert', + methodKind: 'class' as const, + parameters: [receiverModel, original.parameters[0]!], + overloads: original.overloads?.map(overload => ({ + ...overload, + parameters: [receiverModel, ...overload.parameters], + })), + }; + const model: PythonModule = { + ...moduleModel, + functions: [], + classes: [ + { + ...moduleModel.classes[0]!, + name: 'Converter', + kind: 'class', + methods: [method], + properties: [], + }, + ], + }; + const compiled = compileContract(ir.contract, { + module: model, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.diagnostics.some(item => item.path.endsWith('.parameters[0]'))).toBe(false); + expect(compiled.generated.typescript).toContain('"selectable":true'); + expect(compiled.generated.declaration).toContain( + 'static convert(key: string): Promise;' + ); + expect(compiled.generated.typescript).toContain( + 'static async convert(key: unknown): Promise' + ); + + const temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-class-overload-')); + try { + const outputPath = join(temporary, 'fixture.generated.mjs'); + const javascript = ts.transpileModule(compiled.generated.typescript, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(outputPath, javascript, 'utf8'); + setRuntimeBridge({ + async call( + _module: string, + _functionName: string, + _args: unknown[], + _kwargs?: Record, + validate?: (result: T) => void + ): Promise { + const result = 7 as T; + validate?.(result); + return result; + }, + async dispose(): Promise {}, + }); + const generated = (await import(pathToFileURL(outputPath).href)) as { + Converter: { convert: (key: string | number) => Promise }; + }; + await expect(generated.Converter.convert('key')).rejects.toThrow(BridgeValidationError); + await expect(generated.Converter.convert(2)).resolves.toBe(7); + } finally { + clearRuntimeBridge(); + await rm(temporary, { recursive: true, force: true }); + } + }); + + it('validates a generated scalar float16 wrapper from the HTTP codec proof', async () => { + const source = rawIr.functions[1]!; + const ir = validateIrContract( + { + ...rawIr, + functions: [ + { + ...source, + name: 'scalar_value', + qualname: 'fixture.scalar_value', + returns: 'numpy.typing.NDArray[numpy.float16]', + }, + ], + classes: [], + }, + 'scalar contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const scalarType: PythonType = { + kind: 'generic', + name: 'NDArray', + module: 'numpy.typing', + typeArgs: [{ kind: 'custom', name: 'float16', module: 'numpy' }], + }; + const original = moduleModel.functions[1]!; + const model: PythonModule = { + ...moduleModel, + classes: [], + functions: [ + { + ...original, + name: 'scalar_value', + returnType: scalarType, + signature: { ...original.signature, returnType: scalarType }, + }, + ], + }; + const compiled = compileContract(ir.contract, { + module: model, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.generated.typescript).toContain('"marker":"ndarray","dtype":"float16"'); + expect(compiled.generated.declaration).toContain( + 'scalarValue(): Promise<__tywrapFloat16Value>' + ); + + let dtype = 'float16'; + let requestId = 0; + const server = createServer((request, response) => { + request.resume(); + response.setHeader('content-type', 'application/json'); + response.end( + JSON.stringify({ + id: ++requestId, + result: { + __tywrap__: 'ndarray', + codecVersion: 1, + encoding: 'json', + shape: [], + dtype, + data: 1.5, + }, + }) + ); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const address = server.address() as AddressInfo; + const bridge = new HttpBridge({ baseURL: `http://127.0.0.1:${address.port}` }); + const temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-scalar-proof-')); + try { + const outputPath = join(temporary, 'fixture.generated.mjs'); + const javascript = ts.transpileModule(compiled.generated.typescript, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(outputPath, javascript, 'utf8'); + setRuntimeBridge(bridge); + const generated = (await import(pathToFileURL(outputPath).href)) as { + scalarValue: () => Promise; + }; + await expect(generated.scalarValue()).resolves.toBe(1.5); + dtype = 'float32'; + await expect(generated.scalarValue()).rejects.toThrow(BridgeValidationError); + } finally { + clearRuntimeBridge(); + await bridge.dispose(); + await new Promise((resolve, reject) => + server.close(error => (error ? reject(error) : resolve())) + ); + await rm(temporary, { recursive: true, force: true }); + } + }); + + it('uses revision 2 for selected unions and fixed heterogeneous tuples', () => { + const union = DEFAULT_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.functions[0].returns', + logicalType: { + kind: 'union', + types: [ + { kind: 'primitive', name: 'str' }, + { kind: 'primitive', name: 'int' }, + ], + }, + }); + const tuple = DEFAULT_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.functions[1].returns', + logicalType: { + kind: 'collection', + name: 'tuple', + itemTypes: [ + { kind: 'primitive', name: 'int' }, + { kind: 'primitive', name: 'str' }, + ], + }, + }); + + expect(union).toMatchObject({ + status: 'supported', + value: { kind: 'union', options: [{ kind: 'string' }, { kind: 'integer' }] }, + }); + expect(tuple).toMatchObject({ + status: 'supported', + value: { kind: 'tuple', items: [{ kind: 'integer' }, { kind: 'string' }] }, + }); + }); + + it('requires dtype evidence before selecting the float16 scientific contract', () => { + const resolve = (logicalType: PythonType) => + DEFAULT_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.functions[0].returns', + logicalType, + }); + + expect(resolve({ kind: 'custom', name: 'ndarray', module: 'numpy' })).toMatchObject({ + status: 'unresolved', + }); + expect(resolve({ kind: 'custom', name: 'Tensor', module: 'torch' })).toMatchObject({ + status: 'unresolved', + }); + expect( + resolve({ + kind: 'generic', + name: 'NDArray', + module: 'numpy', + typeArgs: [{ kind: 'custom', name: 'float16', module: 'numpy' }], + }) + ).toMatchObject({ + status: 'supported', + value: { kind: 'ndarray-float16', dtype: 'float16' }, + }); + expect( + resolve( + parseAnnotationToPythonType( + 'numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[numpy.float16]]' + ) + ) + ).toMatchObject({ + status: 'supported', + value: { kind: 'ndarray-float16', dtype: 'float16' }, + }); + expect( + resolve( + parseAnnotationToPythonType( + 'numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[numpy.float32]]' + ) + ) + ).toMatchObject({ status: 'unresolved' }); + expect( + resolve( + parseAnnotationToPythonType( + 'numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[external.float16]]' + ) + ) + ).toMatchObject({ status: 'unresolved' }); + expect( + resolve( + parseAnnotationToPythonType( + 'numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[torch.float16]]' + ) + ) + ).toMatchObject({ status: 'unresolved' }); + }); + + it('keeps the existing bytes RPC shape in the value contract', () => { + const resolution = DEFAULT_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.functions[0].returns', + logicalType: { kind: 'primitive', name: 'bytes' }, + }); + expect(resolution).toMatchObject({ + status: 'supported', + value: { kind: 'bytes', wire: 'base64-envelope', decodedAs: 'Uint8Array' }, + }); + }); + + it('matches the outer Torch dtype recorded by the decoder', () => { + const tensorType: PythonType = { + kind: 'generic', + name: 'Tensor', + module: 'torch', + typeArgs: [{ kind: 'custom', name: 'float16', module: 'torch' }], + }; + const resolution = DEFAULT_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.functions[0].returns', + logicalType: tensorType, + }); + expect(resolution.status).toBe('supported'); + if (resolution.status !== 'supported') { + return; + } + const generated = new CodeGenerator().generateModuleDefinition({ + ...moduleModel, + classes: [], + functions: [ + { + ...moduleModel.functions[1]!, + name: 'tensorValue', + returnType: tensorType, + callableContract: { + parameterValues: [], + returnValue: resolution.value, + overloads: [], + }, + }, + ], + }); + expect(generated.typescript).toContain('"marker":"torch.tensor","dtype":"torch.float16"'); + expect(generated.declaration).toContain('tensorValue(): Promise<__tywrapFloat16Tensor>'); + expect( + DEFAULT_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.functions[0].returns', + logicalType: { + ...tensorType, + typeArgs: [{ kind: 'custom', name: 'float16', module: 'external' }], + }, + }) + ).toMatchObject({ status: 'unresolved' }); + }); + + it('accepts only the evaluated torch.HalfTensor class as an exact float16 annotation', () => { + const resolve = (annotation: string) => + DEFAULT_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.functions[0].returns', + logicalType: parseAnnotationToPythonType(annotation), + }); + expect(resolve('torch.HalfTensor')).toMatchObject({ + status: 'supported', + value: { + kind: 'torch-float16', + dtype: 'torch.float16', + value: { kind: 'ndarray-float16', dtype: 'float16' }, + }, + }); + expect(resolve('torch.FloatTensor')).toMatchObject({ status: 'unresolved' }); + expect(resolve('foreign.HalfTensor')).toMatchObject({ status: 'unresolved' }); + expect(resolve('HalfTensor')).toMatchObject({ status: 'unresolved' }); + }); + + it('rejects a Torch float16 response with a mismatched nested dtype', async () => { + const source = rawIr.functions[1]!; + const ir = validateIrContract( + { + ...rawIr, + functions: [ + { + ...source, + name: 'tensor_value', + qualname: 'fixture.tensor_value', + returns: 'torch.Tensor[torch.float16]', + }, + ], + classes: [], + }, + 'Torch contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const tensorType: PythonType = { + kind: 'generic', + name: 'Tensor', + module: 'torch', + typeArgs: [{ kind: 'custom', name: 'float16', module: 'torch' }], + }; + const original = moduleModel.functions[1]!; + const model: PythonModule = { + ...moduleModel, + classes: [], + functions: [ + { + ...original, + name: 'tensor_value', + returnType: tensorType, + signature: { ...original.signature, returnType: tensorType }, + }, + ], + }; + const compiled = compileContract(ir.contract, { + module: model, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.generated.typescript).toContain( + '"marker":"torch.tensor","dtype":"torch.float16"' + ); + + let nestedDtype = 'float16'; + let requestId = 0; + const server = createServer((request, response) => { + request.resume(); + response.setHeader('content-type', 'application/json'); + response.end( + JSON.stringify({ + id: ++requestId, + result: { + __tywrap__: 'torch.tensor', + codecVersion: 1, + encoding: 'ndarray', + shape: [], + dtype: 'torch.float16', + device: 'cpu', + value: { + __tywrap__: 'ndarray', + codecVersion: 1, + encoding: 'json', + shape: [], + dtype: nestedDtype, + data: 1.5, + }, + }, + }) + ); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const address = server.address() as AddressInfo; + const bridge = new HttpBridge({ baseURL: `http://127.0.0.1:${address.port}` }); + const temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-torch-proof-')); + try { + const outputPath = join(temporary, 'fixture.generated.mjs'); + const javascript = ts.transpileModule(compiled.generated.typescript, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(outputPath, javascript, 'utf8'); + setRuntimeBridge(bridge); + const generated = (await import(pathToFileURL(outputPath).href)) as { + tensorValue: () => Promise<{ data: number; dtype: string }>; + }; + await expect(generated.tensorValue()).resolves.toMatchObject({ + data: 1.5, + dtype: 'torch.float16', + }); + nestedDtype = 'float32'; + await expect(generated.tensorValue()).rejects.toThrow(/value\.dtype.*must be "float16"/); + } finally { + clearRuntimeBridge(); + await bridge.dispose(); + await new Promise((resolve, reject) => + server.close(error => (error ? reject(error) : resolve())) + ); + await rm(temporary, { recursive: true, force: true }); + } + }); + + it('keeps supported coroutine results and degrades unadapted dataclass outputs', () => { + const validation = validateIrContract(rawIr, 'fixture contract'); + expect(validation.ok).toBe(true); + if (!validation.ok) { + return; + } + + const compiled = compileContract(validation.contract, { + module: moduleModel, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + + expect(compiled.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ code: 'dataclass-unsupported', path: '$.functions[3].returns' }), + ]) + ); + expect( + compiled.diagnostics.some(diagnostic => diagnostic.code === 'coroutine-unsupported') + ).toBe(false); + expect(compiled.module.functions[2]?.returnType).toEqual({ kind: 'primitive', name: 'str' }); + expect(compiled.generated.declaration).toContain('asyncValue(): Promise'); + expect(compiled.callables[2]?.requiredCapabilities).toContain('coroutine-execution'); + expect(compiled.module.functions[3]?.returnType).toEqual({ + kind: 'custom', + name: 'Any', + module: 'typing', + }); + }); + + it('degrades coroutine results when the execution capability is unavailable', () => { + const validation = validateIrContract(rawIr, 'fixture contract'); + expect(validation.ok).toBe(true); + if (!validation.ok) { + return; + } + + const compiled = compileContract(validation.contract, { + module: moduleModel, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES.map(capability => + capability.name === 'coroutine-execution' ? { ...capability, available: false } : capability + ), + }); + + expect(compiled.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ code: 'coroutine-unsupported', path: '$.functions[2].returns' }), + ]) + ); + expect(compiled.module.functions[2]?.returnType).toEqual({ + kind: 'custom', + name: 'Any', + module: 'typing', + }); + expect(compiled.generated.declaration).toContain('asyncValue(): Promise'); + }); + + it('does not promise a TypeScript object for an unconstrained Python object result', async () => { + const source = rawIr.functions[1]!; + const ir = validateIrContract( + { + ...rawIr, + functions: [ + { + ...source, + name: 'object_value', + qualname: 'fixture.object_value', + returns: 'object', + }, + ], + classes: [], + }, + 'object result contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const compiled = compileContract(ir.contract, { + module: { + ...moduleModel, + classes: [], + functions: [{ ...moduleModel.functions[1]!, name: 'object_value' }], + }, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ code: 'conversion-unresolved', path: '$.functions[0].returns' }), + ]) + ); + expect(compiled.generated.declaration).toContain('objectValue(): Promise'); + expect(compiled.generated.typescript).toContain('createReturnValidator({"kind":"any"}'); + + let nestedList: ReturnType | undefined; + for (const annotation of ['list[object]', 'dict[str, object]']) { + const nested = validateIrContract( + { + ...rawIr, + functions: [ + { + ...source, + name: 'object_value', + qualname: 'fixture.object_value', + returns: annotation, + }, + ], + classes: [], + }, + 'nested object result contract' + ); + expect(nested.ok).toBe(true); + if (!nested.ok) { + continue; + } + const nestedCompiled = compileContract(nested.contract, { + module: { + ...moduleModel, + classes: [], + functions: [{ ...moduleModel.functions[1]!, name: 'object_value' }], + }, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(nestedCompiled.generated.declaration).toContain('objectValue(): Promise'); + expect(nestedCompiled.generated.typescript).toContain( + annotation.startsWith('list') + ? 'createReturnValidator({"kind":"array","element":{"kind":"any"}}' + : 'createReturnValidator({"kind":"record","values":{"kind":"any"}}' + ); + if (annotation.startsWith('list')) { + nestedList = nestedCompiled; + } + } + + let requestId = 0; + const server = createServer((request, response) => { + request.resume(); + response.setHeader('content-type', 'application/json'); + response.end(JSON.stringify({ id: ++requestId, result: 'a valid Python object' })); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const address = server.address() as AddressInfo; + const bridge = new HttpBridge({ baseURL: `http://127.0.0.1:${address.port}` }); + const temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-object-proof-')); + try { + const outputPath = join(temporary, 'fixture.generated.mjs'); + const javascript = ts.transpileModule(compiled.generated.typescript, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(outputPath, javascript, 'utf8'); + setRuntimeBridge(bridge); + const generated = (await import(pathToFileURL(outputPath).href)) as { + objectValue: () => Promise; + }; + await expect(generated.objectValue()).resolves.toBe('a valid Python object'); + if (nestedList) { + const nestedPath = join(temporary, 'nested.generated.mjs'); + await writeFile( + nestedPath, + ts.transpileModule(nestedList.generated.typescript, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText, + 'utf8' + ); + const nestedGenerated = (await import(pathToFileURL(nestedPath).href)) as { + objectValue: () => Promise; + }; + await expect(nestedGenerated.objectValue()).rejects.toThrow(BridgeValidationError); + } + } finally { + clearRuntimeBridge(); + await bridge.dispose(); + await new Promise((resolve, reject) => + server.close(error => (error ? reject(error) : resolve())) + ); + await rm(temporary, { recursive: true, force: true }); + } + }); + + it('keeps generic inputs but uses unknown for unvalidated type-variable results', async () => { + const source = rawIr.functions[1]!; + const typeVar = { + name: 'T', + kind: 'typevar' as const, + bound: null, + constraints: null, + variance: null, + }; + const generic = { + ...source, + name: 'generic_identity', + qualname: 'fixture.generic_identity', + parameters: [ + { name: 'value', kind: 'POSITIONAL_OR_KEYWORD', annotation: '~T', default: false }, + ], + returns: '~T', + type_params: [typeVar], + }; + const nested = { + ...generic, + name: 'generic_nested', + qualname: 'fixture.generic_nested', + parameters: [ + { name: 'value', kind: 'POSITIONAL_OR_KEYWORD', annotation: 'list[~T]', default: false }, + ], + returns: 'list[~T]', + }; + const paramspec = { + ...generic, + name: 'paramspec_apply', + qualname: 'fixture.paramspec_apply', + parameters: [ + { + name: 'callback', + kind: 'POSITIONAL_OR_KEYWORD', + annotation: 'typing.Callable[~P, ~T]', + default: false, + }, + ], + type_params: [ + { name: 'P', kind: 'paramspec' as const, bound: null, constraints: null, variance: null }, + typeVar, + ], + }; + const ir = validateIrContract( + { ...rawIr, functions: [generic, nested, paramspec], classes: [] }, + 'generic result contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const compiled = compileContract(ir.contract, { + module: { + ...moduleModel, + classes: [], + functions: [generic, nested, paramspec].map(func => ({ + ...moduleModel.functions[1]!, + name: func.name, + })), + }, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ code: 'conversion-unresolved', path: '$.functions[0].returns' }), + expect.objectContaining({ code: 'conversion-unresolved', path: '$.functions[1].returns' }), + expect.objectContaining({ code: 'conversion-unresolved', path: '$.functions[2].returns' }), + ]) + ); + expect(compiled.generated.declaration).toContain( + 'genericIdentity(value: T): Promise' + ); + expect(compiled.generated.declaration).toContain( + 'genericNested(value: T[]): Promise' + ); + expect(compiled.generated.declaration).toMatch( + /paramspecApply<[^>]*>\([^\n]*\): Promise/ + ); + + let requestId = 0; + const server = createServer((request, response) => { + request.resume(); + response.setHeader('content-type', 'application/json'); + response.end(JSON.stringify({ id: ++requestId, result: 'not the numeric input' })); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const address = server.address() as AddressInfo; + const bridge = new HttpBridge({ baseURL: `http://127.0.0.1:${address.port}` }); + const temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-generic-proof-')); + try { + const outputPath = join(temporary, 'fixture.generated.mjs'); + const javascript = ts.transpileModule(compiled.generated.typescript, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(outputPath, javascript, 'utf8'); + const declarationPath = join(temporary, 'fixture.generated.d.ts'); + const consumerPath = join(temporary, 'consumer.ts'); + await writeFile(declarationPath, compiled.generated.declaration, 'utf8'); + await writeFile( + consumerPath, + "import { genericIdentity } from './fixture.generated.js';\nconst numeric: Promise = genericIdentity(42);\nvoid numeric;\n", + 'utf8' + ); + const program = ts.createProgram([consumerPath], { + noEmit: true, + strict: true, + skipLibCheck: true, + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + types: [], + }); + expect(ts.getPreEmitDiagnostics(program).map(diagnostic => diagnostic.code)).toContain(2322); + setRuntimeBridge(bridge); + const generated = (await import(pathToFileURL(outputPath).href)) as { + genericIdentity: (value: T) => Promise; + }; + await expect(generated.genericIdentity(42)).resolves.toBe('not the numeric input'); + } finally { + clearRuntimeBridge(); + await bridge.dispose(); + await new Promise((resolve, reject) => + server.close(error => (error ? reject(error) : resolve())) + ); + await rm(temporary, { recursive: true, force: true }); + } + }); + + it('keeps existing marker and literal checks when the declaration falls back to unknown', async () => { + const source = rawIr.functions[1]!; + const annotations = [ + { name: 'dataframe_value', returns: 'pandas.DataFrame' }, + { name: 'literal_value', returns: "typing.Literal['x']" }, + ]; + const ir = validateIrContract( + { + ...rawIr, + functions: annotations.map(({ name, returns }) => ({ + ...source, + name, + qualname: `fixture.${name}`, + returns, + })), + classes: [], + }, + 'unresolved validation contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const compiled = compileContract(ir.contract, { + module: { + ...moduleModel, + classes: [], + functions: annotations.map(({ name }) => ({ ...moduleModel.functions[1]!, name })), + }, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.generated.declaration).toContain('dataframeValue(): Promise'); + expect(compiled.generated.declaration).toContain('literalValue(): Promise'); + expect(compiled.generated.typescript).toContain('"marker":"dataframe"'); + expect(compiled.generated.typescript).toContain('"kind":"literal","value":"x"'); + + const temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-fallback-proof-')); + try { + const outputPath = join(temporary, 'fixture.generated.mjs'); + const javascript = ts.transpileModule(compiled.generated.typescript, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(outputPath, javascript, 'utf8'); + setRuntimeBridge({ + async call( + _module: string, + functionName: string, + _args: unknown[], + _kwargs?: Record, + validate?: (result: T) => void + ): Promise { + const result = (functionName === 'literal_value' ? 'y' : {}) as T; + validate?.(result); + return result; + }, + async dispose(): Promise {}, + }); + const generated = (await import(pathToFileURL(outputPath).href)) as { + dataframeValue: () => Promise; + literalValue: () => Promise; + }; + await expect(generated.dataframeValue()).rejects.toThrow(BridgeValidationError); + await expect(generated.literalValue()).rejects.toThrow(BridgeValidationError); + } finally { + clearRuntimeBridge(); + await rm(temporary, { recursive: true, force: true }); + } + }); + + it('resolves selected local TypedDict fields and simple aliases through revision 2', async () => { + const source = rawIr.functions[1]!; + const point = rawIr.classes[0]!; + const ir = validateIrContract( + { + ...rawIr, + functions: [ + { + ...source, + name: 'payload_value', + qualname: 'fixture.payload_value', + returns: 'Payload', + }, + { ...source, name: 'user_id', qualname: 'fixture.user_id', returns: 'UserId' }, + ], + classes: [ + { + ...point, + name: 'Payload', + qualname: 'fixture.Payload', + typed_dict: true, + is_dataclass: false, + fields: [ + { name: 'x', kind: 'FIELD', annotation: 'int', default: false }, + { name: 'label', kind: 'FIELD', annotation: 'str', default: true }, + ], + }, + ], + type_aliases: [{ name: 'UserId', definition: 'int', is_generic: false, type_params: [] }], + }, + 'selected named values contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const compiled = compileContract(ir.contract, { + module: { + ...moduleModel, + functions: ['payload_value', 'user_id'].map(name => ({ + ...moduleModel.functions[1]!, + name, + })), + classes: [{ ...moduleModel.classes[0]!, name: 'Payload' }], + typeAliases: [{ name: 'UserId', type: { kind: 'primitive', name: 'int' } }], + }, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.diagnostics).toEqual([]); + expect(compiled.generated.declaration).toContain('payloadValue(): Promise'); + expect(compiled.generated.declaration).toContain('userId(): Promise'); + expect(compiled.callables[0]?.result.resolution).toMatchObject({ + status: 'supported', + value: { + kind: 'record', + fields: [ + { name: 'x', required: true, value: { kind: 'integer' } }, + { name: 'label', required: false, value: { kind: 'string' } }, + ], + }, + }); + expect(compiled.callables[1]?.result.resolution).toMatchObject({ + status: 'supported', + value: { kind: 'integer', constraint: 'safe-integer' }, + }); + + const temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-named-proof-')); + try { + const outputPath = join(temporary, 'fixture.generated.mjs'); + const javascript = ts.transpileModule(compiled.generated.typescript, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(outputPath, javascript, 'utf8'); + setRuntimeBridge({ + async call( + _module: string, + functionName: string, + _args: unknown[], + _kwargs?: Record, + validate?: (result: T) => void + ): Promise { + const result = ( + functionName === 'user_id' ? Number.MAX_SAFE_INTEGER + 1 : { x: 'bad' } + ) as T; + validate?.(result); + return result; + }, + async dispose(): Promise {}, + }); + const generated = (await import(pathToFileURL(outputPath).href)) as { + payloadValue: () => Promise<{ x: number; label?: string }>; + userId: () => Promise; + }; + await expect(generated.payloadValue()).rejects.toThrow(BridgeValidationError); + await expect(generated.userId()).rejects.toThrow(BridgeValidationError); + } finally { + clearRuntimeBridge(); + await rm(temporary, { recursive: true, force: true }); + } + }); + + it('composes nested local records and aliases, but stops cycles and foreign names', () => { + const source = rawIr.functions[1]!; + const point = rawIr.classes[0]!; + const typedDict = (name: string, annotation: string) => ({ + ...point, + name, + qualname: `fixture.${name}`, + typed_dict: true, + is_dataclass: false, + fields: [{ name: 'value', kind: 'FIELD', annotation, default: false }], + }); + const returns = [ + ['nested_values', 'list[Outer]'], + ['alias_values', 'AliasAlias'], + ['cycle_values', 'Loop'], + ['foreign_values', 'foreign.Outer'], + ['self_values', 'SelfRef'], + ['qualified_values', 'fixture.Outer'], + ] as const; + const ir = validateIrContract( + { + ...rawIr, + functions: returns.map(([name, annotation]) => ({ + ...source, + name, + qualname: `fixture.${name}`, + returns: annotation, + })), + classes: [ + typedDict('Child', 'int'), + typedDict('Outer', 'Child'), + typedDict('SelfRef', 'SelfRef'), + ], + type_aliases: [ + { name: 'UserId', definition: 'int', is_generic: false, type_params: [] }, + { name: 'AliasAlias', definition: 'UserId', is_generic: false, type_params: [] }, + { name: 'Loop', definition: 'Loop', is_generic: false, type_params: [] }, + ], + }, + 'composed named values contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const compiled = compileContract(ir.contract, { + module: { + ...moduleModel, + functions: returns.map(([name]) => ({ ...moduleModel.functions[1]!, name })), + classes: ['Child', 'Outer', 'SelfRef'].map(name => ({ + ...moduleModel.classes[0]!, + name, + })), + typeAliases: ['UserId', 'AliasAlias', 'Loop'].map(name => ({ + name, + type: { kind: 'custom' as const, name: 'Any' }, + })), + }, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.callables[0]?.result.resolution).toMatchObject({ + status: 'supported', + value: { + kind: 'sequence', + item: { + kind: 'record', + fields: [ + { + name: 'value', + value: { + kind: 'record', + fields: [{ name: 'value', value: { kind: 'integer' } }], + }, + }, + ], + }, + }, + }); + expect(compiled.callables[1]?.result.resolution).toMatchObject({ + status: 'supported', + value: { kind: 'integer', constraint: 'safe-integer' }, + }); + expect(compiled.callables[2]?.result.resolution.status).toBe('unresolved'); + expect(compiled.callables[3]?.result.resolution.status).toBe('unresolved'); + expect(compiled.callables[4]?.result.resolution.status).toBe('unresolved'); + expect(compiled.callables[5]?.result.resolution.status).toBe('supported'); + expect(compiled.generated.declaration).toContain('nestedValues(): Promise'); + expect(compiled.generated.declaration).toContain('aliasValues(): Promise'); + expect(compiled.generated.declaration).toContain('cycleValues(): Promise'); + expect(compiled.generated.declaration).toContain('foreignValues(): Promise'); + expect(compiled.generated.declaration).toContain('selfValues(): Promise'); + expect(compiled.generated.declaration).toContain('qualifiedValues(): Promise'); + expect(compiled.generated.typescript).toContain( + 'const __validateforeign_valuesResult = createReturnValidator({"kind":"any"}' + ); + + const rejectIntegers: typeof DEFAULT_VALUE_CONVERSION = { + revision: DEFAULT_VALUE_CONVERSION.revision, + resolve(request) { + if (request.logicalType.kind === 'primitive' && request.logicalType.name === 'int') { + return { + status: 'unsupported', + reason: 'This configured conversion declines integers.', + guidance: 'Use a different conversion.', + }; + } + return DEFAULT_VALUE_CONVERSION.resolve(request); + }, + }; + const declined = compileContract(ir.contract, { + module: { + ...moduleModel, + functions: returns.map(([name]) => ({ ...moduleModel.functions[1]!, name })), + classes: ['Child', 'Outer', 'SelfRef'].map(name => ({ + ...moduleModel.classes[0]!, + name, + })), + typeAliases: ['UserId', 'AliasAlias', 'Loop'].map(name => ({ + name, + type: { kind: 'custom' as const, name: 'Any' }, + })), + }, + generator: new CodeGenerator(), + conversion: rejectIntegers, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(declined.callables[0]?.result.resolution.status).toBe('unsupported'); + expect(declined.callables[1]?.result.resolution.status).toBe('unsupported'); + expect(declined.generated.declaration).toContain('nestedValues(): Promise'); + }); + + it('bounds local alias expansion when a converter leaves custom names unresolved', () => { + const aliases = Array.from({ length: 70 }, (_, index) => ({ + name: `Alias${index}`, + definition: index === 69 ? 'External' : `Alias${index + 1}`, + is_generic: false, + type_params: [], + })); + const source = rawIr.functions[1]!; + const ir = validateIrContract( + { + ...rawIr, + functions: [ + { ...source, name: 'alias_chain', qualname: 'fixture.alias_chain', returns: 'Alias0' }, + ], + type_aliases: aliases, + }, + 'bounded alias chain contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const unresolvedCustom: typeof DEFAULT_VALUE_CONVERSION = { + revision: DEFAULT_VALUE_CONVERSION.revision, + resolve(request) { + if (request.logicalType.kind === 'custom') { + return { status: 'unresolved', annotation: request.logicalType.name }; + } + return DEFAULT_VALUE_CONVERSION.resolve(request); + }, + }; + const compiled = compileContract(ir.contract, { + module: { + ...moduleModel, + functions: [{ ...moduleModel.functions[1]!, name: 'alias_chain' }], + classes: [], + typeAliases: aliases.map(alias => ({ + name: alias.name, + type: { kind: 'custom' as const, name: 'Any' }, + })), + }, + generator: new CodeGenerator(), + conversion: unresolvedCustom, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.callables[0]?.result.resolution).toMatchObject({ + status: 'unsupported', + reason: 'Revision 2 limits value contracts to 64 nested nodes.', + }); + }); + + it('treats a variadic integer tuple as the supported sequence contract', () => { + const logicalType = parseAnnotationToPythonType('tuple[int, ...]'); + expect( + DEFAULT_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.functions[0].returns', + logicalType, + }) + ).toMatchObject({ + status: 'supported', + value: { + kind: 'sequence', + item: { kind: 'integer', constraint: 'safe-integer' }, + }, + }); + }); + it('rejects unions whose marker wire can decode as a different value', async () => { + const annotations = [ + 'bytes | dict[str, str]', + 'list[bytes] | list[dict[str, str]]', + 'tuple[bytes] | tuple[dict[str, str]]', + 'dict[str, bytes] | dict[str, dict[str, str]]', + ]; + for (const annotation of annotations) { + expect( + DEFAULT_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.returns', + logicalType: parseAnnotationToPythonType(annotation), + }) + ).toMatchObject({ + status: 'unsupported', + reason: 'Union alternatives can share a wire value but decode differently.', + }); + } + for (const annotation of ['int | float', 'bytes | str', 'bytes | dict[str, int]']) { + expect( + DEFAULT_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.returns', + logicalType: parseAnnotationToPythonType(annotation), + }).status + ).toBe('supported'); + } + const tagged: typeof DEFAULT_VALUE_CONVERSION = { + revision: DEFAULT_VALUE_CONVERSION.revision, + resolve(request) { + if (request.logicalType.kind === 'custom' && request.logicalType.name === 'IntTag') { + return { + status: 'supported', + value: { + kind: 'record', + wire: 'json', + decodedAs: 'object', + fields: [ + { + name: 'tag', + required: true, + value: { + kind: 'integer', + wire: 'json', + decodedAs: 'number', + constraint: 'safe-integer', + }, + }, + { + name: 'payload', + required: true, + value: { kind: 'bytes', wire: 'base64-envelope', decodedAs: 'Uint8Array' }, + }, + ], + }, + }; + } + if (request.logicalType.kind === 'custom' && request.logicalType.name === 'StringTag') { + return { + status: 'supported', + value: { + kind: 'record', + wire: 'json', + decodedAs: 'object', + fields: [ + { + name: 'tag', + required: true, + value: { kind: 'string', wire: 'json', decodedAs: 'string' }, + }, + { + name: 'payload', + required: true, + value: { + kind: 'record', + wire: 'json', + decodedAs: 'object', + fields: [], + additionalValues: { kind: 'string', wire: 'json', decodedAs: 'string' }, + }, + }, + ], + }, + }; + } + if ( + request.logicalType.kind === 'custom' && + (request.logicalType.name === 'ExtraRecord' || + request.logicalType.name === 'ExtraRecordValues') + ) { + return { + status: 'supported', + value: { + kind: 'record', + wire: 'json', + decodedAs: 'object', + fields: [ + { + name: '__type__', + required: true, + value: { kind: 'string', wire: 'json', decodedAs: 'string' }, + }, + { + name: 'encoding', + required: true, + value: { kind: 'string', wire: 'json', decodedAs: 'string' }, + }, + { + name: 'data', + required: true, + value: { kind: 'string', wire: 'json', decodedAs: 'string' }, + }, + { + name: 'extra', + required: true, + value: { + kind: 'integer', + wire: 'json', + decodedAs: 'number', + constraint: 'safe-integer', + }, + }, + ], + additionalValues: + request.logicalType.name === 'ExtraRecordValues' + ? { + kind: 'union', + wire: 'selected-option', + decodedAs: 'selected-option', + options: [ + { kind: 'string', wire: 'json', decodedAs: 'string' }, + { + kind: 'integer', + wire: 'json', + decodedAs: 'number', + constraint: 'safe-integer', + }, + ], + } + : undefined, + }, + }; + } + if ( + request.logicalType.kind === 'custom' && + (request.logicalType.name === 'NdarrayRecord' || + request.logicalType.name === 'NdarrayVersionRecord' || + request.logicalType.name === 'TorchRecord') + ) { + const stringValue = { kind: 'string', wire: 'json', decodedAs: 'string' } as const; + const integerValue = { + kind: 'integer', + wire: 'json', + decodedAs: 'number', + constraint: 'safe-integer', + } as const; + const scientific = request.logicalType.name !== 'TorchRecord'; + return { + status: 'supported', + value: { + kind: 'record', + wire: 'json', + decodedAs: 'object', + fields: [ + { name: '__tywrap__', required: true, value: stringValue }, + { name: 'encoding', required: true, value: stringValue }, + { + name: scientific ? 'data' : 'value', + required: true, + value: scientific + ? { kind: 'sequence', wire: 'json', decodedAs: 'array', item: integerValue } + : { kind: 'record', wire: 'json', decodedAs: 'object', fields: [] }, + }, + { + name: 'codecVersion', + required: request.logicalType.name === 'NdarrayVersionRecord', + value: stringValue, + }, + ...(scientific + ? [ + { + name: 'shape', + required: true, + value: { + kind: 'sequence' as const, + wire: 'json' as const, + decodedAs: 'array' as const, + item: integerValue, + }, + }, + { name: 'dtype', required: true, value: stringValue }, + ] + : [{ name: 'device', required: false, value: integerValue }]), + ], + }, + }; + } + return DEFAULT_VALUE_CONVERSION.resolve({ ...request, resolveNested: tagged.resolve }); + }, + }; + expect( + tagged.resolve({ + direction: 'output', + path: '$.returns', + logicalType: parseAnnotationToPythonType('IntTag | StringTag'), + }).status + ).toBe('supported'); + for (const annotation of ['bytes | ExtraRecord', 'bytes | ExtraRecordValues']) { + expect( + tagged.resolve({ + direction: 'output', + path: '$.returns', + logicalType: parseAnnotationToPythonType(annotation), + }) + ).toMatchObject({ + status: 'unsupported', + reason: 'Union alternatives can share a wire value but decode differently.', + }); + } + for (const annotation of [ + 'numpy.NDArray[numpy.float16] | NdarrayRecord', + 'torch.Tensor[torch.float16] | TorchRecord', + ]) { + expect( + tagged.resolve({ + direction: 'output', + path: '$.returns', + logicalType: parseAnnotationToPythonType(annotation), + }) + ).toMatchObject({ + status: 'unsupported', + reason: 'Union alternatives can share a wire value but decode differently.', + }); + } + expect( + tagged.resolve({ + direction: 'output', + path: '$.returns', + logicalType: parseAnnotationToPythonType( + 'numpy.NDArray[numpy.float16] | NdarrayVersionRecord' + ), + }).status + ).toBe('supported'); + const decoded = await new BridgeCodec().decodeResponseAsync( + JSON.stringify({ + id: 1, + protocol: 'tywrap/1', + result: { __type__: 'bytes', encoding: 'base64', data: 'eA==', extra: 1 }, + }) + ); + expect(decoded).toEqual(Uint8Array.from([120])); + const ndarrayDecoded = await new BridgeCodec().decodeResponseAsync( + JSON.stringify({ + id: 2, + protocol: 'tywrap/1', + result: { + __tywrap__: 'ndarray', + encoding: 'json', + data: [1], + shape: [1], + dtype: 'float16', + }, + }) + ); + expect(ndarrayDecoded).toEqual([1]); + const torchDecoded = await new BridgeCodec().decodeResponseAsync( + JSON.stringify({ + id: 3, + protocol: 'tywrap/1', + result: { + __tywrap__: 'torch.tensor', + encoding: 'ndarray', + value: { + __tywrap__: 'ndarray', + encoding: 'json', + data: [1], + shape: [1], + dtype: 'float16', + }, + shape: [1], + dtype: 'torch.float16', + }, + }) + ); + expect(torchDecoded).toMatchObject({ data: [1], shape: [1], dtype: 'torch.float16' }); + + const source = rawIr.functions[1]!; + const ir = validateIrContract( + { + ...rawIr, + functions: [ + { + ...source, + name: 'ambiguous_wire', + qualname: 'fixture.ambiguous_wire', + returns: 'bytes | dict[str, str]', + }, + ], + }, + 'ambiguous union wire contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const module = { + ...moduleModel, + functions: [{ ...moduleModel.functions[1]!, name: 'ambiguous_wire' }], + classes: [], + }; + const compiled = compileContract(ir.contract, { + module, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.callables[0]?.result.resolution.status).toBe('unsupported'); + expect(compiled.diagnostics).toContainEqual( + expect.objectContaining({ + severity: 'error', + code: 'conversion-unsupported', + path: '$.functions[0].returns', + }) + ); + expect(compiled.generated.declaration).toContain('ambiguousWire(): Promise'); + expect(compiled.generated.typescript).toContain( + 'const __validateambiguous_wireResult = createReturnValidator({"kind":"any"}' + ); + }); + + it('uses revision 3 for explicit nested bigint callables only', () => { + const source = rawIr.functions[1]!; + const ir = validateIrContract( + { + ...rawIr, + functions: [ + { + ...source, + name: 'combine_exact', + qualname: 'fixture.combine_exact', + parameters: [ + { name: 'value', kind: 'POSITIONAL_OR_KEYWORD', annotation: 'int', default: false }, + { + name: 'nested', + kind: 'POSITIONAL_OR_KEYWORD', + annotation: 'list[int]', + default: false, + }, + { name: 'flag', kind: 'POSITIONAL_OR_KEYWORD', annotation: 'bool', default: false }, + { name: 'ratio', kind: 'POSITIONAL_OR_KEYWORD', annotation: 'float', default: false }, + ], + returns: 'int', + }, + ], + }, + 'exact integer callable contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const module = { + ...moduleModel, + functions: [{ ...moduleModel.functions[1]!, name: 'combine_exact' }], + classes: [], + }; + const options = { + module, + generator: new CodeGenerator(), + conversion: EXACT_INTEGER_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }; + expect(() => compileContract(ir.contract, options)).toThrow( + /exact-integer-adapter is unavailable/ + ); + const capabilities = DEFAULT_CALLABLE_CAPABILITIES.map(capability => + capability.name === 'exact-integer-adapter' ? { ...capability, available: true } : capability + ); + const exact = compileContract(ir.contract, { ...options, capabilities }); + expect(exact.callables[0]?.requiredCapabilities).toContain('exact-integer-adapter'); + expect(exact.callables[0]?.parameters[1]?.resolution).toMatchObject({ + status: 'supported', + value: { kind: 'sequence', item: { kind: 'integer-exact' } }, + }); + expect(exact.generated.declaration).toContain('value: bigint'); + expect(exact.generated.declaration).toContain('nested: bigint[]'); + expect(exact.generated.declaration).toContain('flag: boolean'); + expect(exact.generated.declaration).toContain('ratio: number'); + expect(exact.generated.declaration).toContain('Promise'); + expect(exact.generated.typescript).toContain('"kind":"primitive","type":"bigint"'); + + const defaultContract = compileContract(ir.contract, { + ...options, + conversion: DEFAULT_VALUE_CONVERSION, + }); + expect(defaultContract.generated.declaration).toContain('value: number'); + expect(defaultContract.generated.declaration).toContain('nested: number[]'); + expect(defaultContract.generated.declaration).toContain('Promise'); + }); + + it('keeps exact integer tags disjoint from record union options', () => { + expect( + EXACT_INTEGER_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.returns', + logicalType: parseAnnotationToPythonType('int | dict[str, str]'), + }) + ).toMatchObject({ + status: 'unsupported', + reason: 'An exact integer tag can overlap a record wire value.', + }); + expect( + EXACT_INTEGER_VALUE_CONVERSION.resolve({ + direction: 'output', + path: '$.returns', + logicalType: parseAnnotationToPythonType('int | bool'), + }) + ).toMatchObject({ status: 'supported', value: { kind: 'union' } }); + }); + + it('keeps exact integer depth bounded before resolving a leaf', () => { + const request = { + direction: 'output' as const, + path: '$.returns', + logicalType: parseAnnotationToPythonType('int'), + }; + expect(EXACT_INTEGER_VALUE_CONVERSION.resolve({ ...request, depth: 64 }).status).toBe( + 'supported' + ); + expect(EXACT_INTEGER_VALUE_CONVERSION.resolve({ ...request, depth: 65 })).toMatchObject({ + status: 'unsupported', + reason: 'Revision 3 limits value contracts to 64 nested nodes.', + }); + }); + + it('uses exact input types in static and class method declarations', () => { + const source = rawIr.functions[1]!; + const value = { + name: 'value', + kind: 'POSITIONAL_OR_KEYWORD', + annotation: 'int', + default: false, + }; + const receiver = { + name: 'cls', + kind: 'POSITIONAL_OR_KEYWORD', + annotation: null, + default: false, + }; + const methods = [ + { + ...source, + name: 'static_echo', + qualname: 'fixture.Box.static_echo', + method_kind: 'static', + parameters: [value], + returns: 'int', + }, + { + ...source, + name: 'class_echo', + qualname: 'fixture.Box.class_echo', + method_kind: 'class', + parameters: [receiver, value], + returns: 'int', + overloads: [ + { parameters: [receiver, value], returns: 'int' }, + { + parameters: [receiver, { ...value, annotation: 'str' }], + returns: 'str', + }, + ], + }, + ]; + const ir = validateIrContract( + { + ...rawIr, + functions: [], + classes: [ + { + ...rawIr.classes[0]!, + name: 'Box', + qualname: 'fixture.Box', + methods, + fields: [], + is_dataclass: false, + }, + ], + }, + 'exact integer method contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const original = moduleModel.functions[1]!; + const model: PythonModule = { + ...moduleModel, + functions: [], + classes: [ + { + ...moduleModel.classes[0]!, + name: 'Box', + kind: 'class', + methods: methods.map(method => ({ + ...original, + name: method.name, + methodKind: method.method_kind as 'class' | 'static', + })), + properties: [], + }, + ], + }; + const capabilities = DEFAULT_CALLABLE_CAPABILITIES.map(capability => + capability.name === 'exact-integer-adapter' ? { ...capability, available: true } : capability + ); + const compiled = compileContract(ir.contract, { + module: model, + generator: new CodeGenerator(), + conversion: EXACT_INTEGER_VALUE_CONVERSION, + capabilities, + }); + expect(compiled.generated.declaration).toContain( + 'static staticEcho(value: bigint): Promise;' + ); + expect(compiled.generated.declaration).toContain( + 'static classEcho(value: bigint): Promise;' + ); + expect(compiled.generated.declaration).toContain( + 'static classEcho(value: string): Promise;' + ); + expect(compiled.generated.typescript).toContain( + 'static async staticEcho(value: bigint): Promise' + ); + }); + + it('types exact variadic inputs and rejects an unrepresentable mixed keyword shape', async () => { + const source = rawIr.functions[1]!; + const functions = [ + { + ...source, + name: 'spread_exact', + qualname: 'fixture.spread_exact', + parameters: [{ name: 'values', kind: 'VAR_POSITIONAL', annotation: 'int', default: false }], + returns: 'int', + }, + { + ...source, + name: 'keyword_exact', + qualname: 'fixture.keyword_exact', + parameters: [{ name: 'values', kind: 'VAR_KEYWORD', annotation: 'int', default: false }], + returns: 'int', + }, + ]; + const ir = validateIrContract({ ...rawIr, functions }, 'exact integer variadic contract'); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const module = { + ...moduleModel, + functions: functions.map(func => ({ ...moduleModel.functions[1]!, name: func.name })), + classes: [], + }; + const capabilities = DEFAULT_CALLABLE_CAPABILITIES.map(capability => + capability.name === 'exact-integer-adapter' ? { ...capability, available: true } : capability + ); + const compiled = compileContract(ir.contract, { + module, + generator: new CodeGenerator(), + conversion: EXACT_INTEGER_VALUE_CONVERSION, + capabilities, + }); + expect(compiled.generated.declaration).toContain( + 'spreadExact(...values: bigint[]): Promise' + ); + expect(compiled.generated.declaration).toContain( + 'keywordExact(kwargs?: Record): Promise' + ); + expect(compiled.generated.declaration).not.toContain('unknown[]'); + + const temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-exact-variadic-')); + try { + const declarationPath = join(temporary, 'fixture.generated.d.ts'); + const consumerPath = join(temporary, 'consumer.ts'); + await writeFile(declarationPath, compiled.generated.declaration, 'utf8'); + await writeFile( + consumerPath, + [ + "import { spreadExact, keywordExact } from './fixture.generated.js';", + 'const spread: Promise = spreadExact(1n, 2n);', + 'const keyword: Promise = keywordExact({ value: 1n });', + 'void spread;', + 'void keyword;', + '// @ts-expect-error exact spread values require bigint', + 'spreadExact(1);', + '// @ts-expect-error exact keyword values require bigint', + 'keywordExact({ value: 1 });', + ].join('\n'), + 'utf8' + ); + const program = ts.createProgram([consumerPath], { + noEmit: true, + strict: true, + skipLibCheck: true, + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + types: [], + }); + expect(ts.getPreEmitDiagnostics(program)).toEqual([]); + } finally { + await rm(temporary, { recursive: true, force: true }); + } + + const mixed = validateIrContract( + { + ...rawIr, + functions: [ + { + ...functions[1]!, + parameters: [ + { name: 'flag', kind: 'KEYWORD_ONLY', annotation: 'bool', default: false }, + { name: 'values', kind: 'VAR_KEYWORD', annotation: 'int', default: false }, + ], + }, + ], + }, + 'mixed exact kwargs contract' + ); + expect(mixed.ok).toBe(true); + if (mixed.ok) { + expect(() => + compileContract(mixed.contract, { + module: { ...module, functions: [module.functions[1]!] }, + generator: new CodeGenerator(), + conversion: EXACT_INTEGER_VALUE_CONVERSION, + capabilities, + }) + ).toThrow(/exact \*\*kwargs cannot share a signature/); + } + }); + + it('requires returned dataclass fields even when their constructor has defaults', () => { + const point = rawIr.classes[0]!; + const ir = validateIrContract( + { + ...rawIr, + functions: [], + classes: [ + { + ...point, + fields: [{ ...point.fields[0]!, default: true }, point.fields[1]!], + }, + ], + }, + 'Point default contract' + ); + expect(ir.ok).toBe(true); + if (!ir.ok) { + return; + } + const compiled = compileContract(ir.contract, { + module: { ...moduleModel, functions: [] }, + generator: new CodeGenerator(), + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + expect(compiled.generated.declaration).toContain('x: number;'); + expect(compiled.generated.declaration).not.toContain('x?: number;'); + }); +}); diff --git a/test/client-binding-prototype.test.ts b/test/client-binding-prototype.test.ts new file mode 100644 index 00000000..0b332366 --- /dev/null +++ b/test/client-binding-prototype.test.ts @@ -0,0 +1,554 @@ +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import ts from 'typescript'; +import { BridgeDisposedError } from 'tywrap'; +import { HttpBridge } from 'tywrap/http'; +import { NodeBridge } from 'tywrap/node'; +import { clearRuntimeBridge, getRuntimeBridge, setRuntimeBridge } from 'tywrap/runtime'; + +import { + compileContract, + DEFAULT_CALLABLE_CAPABILITIES, + DEFAULT_VALUE_CONVERSION, +} from '../src/core/callable-compiler.js'; +import { + renderClientBindingPrototype, + type BindingPrototypeCode, +} from '../src/core/client-binding-prototype.js'; +import { CodeGenerator } from '../src/core/generator.js'; +import { validateIrContract } from '../src/core/ir-contract.js'; +import { transformIrToTsModel } from '../src/core/ir-model.js'; +import { createBridgeReloader } from '../src/dev.js'; +import { generate } from '../src/tywrap.js'; +import type { GeneratedCode, PythonModule, RuntimeExecution } from '../src/types/index.js'; +import { getDefaultPythonPath } from '../src/utils/python.js'; +import { processUtils } from '../src/utils/runtime.js'; +import { PYTHON_AVAILABLE } from './helpers/python-probe.js'; + +interface FixtureApi { + environment(): Promise; + createClient(): Promise; + dispose(): Promise; + identity(value: T): Promise; + select(value: string | number): Promise; + scale(value: number, factor?: number): Promise; + kwOnly(kwargs?: { label: string }): Promise; + echoBytes(value: Uint8Array): Promise; + invalidReturn(): Promise; + fail(): Promise; + Client: { label(value: string): Promise }; +} + +interface FixtureHandle { + api: FixtureApi; + dispose(): void; +} + +interface ClientModule { + bindRuntime(runtime: Pick): FixtureHandle; +} + +interface LegacyModule { + environment(): Promise; + scale(value: number, factor?: number): Promise; + kwOnly(kwargs?: { label: string }): Promise; + echoBytes(value: Uint8Array): Promise; + invalidReturn(): Promise; + Client: { label(value: string): Promise }; +} + +class LabeledRuntime implements RuntimeExecution { + disposed = false; + + constructor(readonly label: string) {} + + async call( + _module: string, + _functionName: string, + _args: unknown[], + _kwargs?: Record, + validate?: (result: T) => void + ): Promise { + if (this.disposed) throw new BridgeDisposedError('Bridge has been disposed'); + const result = this.label as T; + validate?.(result); + return result; + } + + async dispose(): Promise { + this.disposed = true; + } +} + +const fixtureA = resolve('test/fixtures/python/binding_a'); +const fixtureB = resolve('test/fixtures/python/binding_b'); +const bridgeScript = resolve('runtime/python_bridge.py'); +const pythonPath = getDefaultPythonPath(); +const defaultExcludedExports = new Set([ + 'dataclass', + 'property', + 'staticmethod', + 'classmethod', + 'abstractmethod', + 'cached_property', +]); + +async function compiledFixture( + outputDir: string, + moduleName: string +): Promise<{ baseline: GeneratedCode; module: PythonModule }> { + const contractPath = join(outputDir, `${moduleName}.contract.json`); + const parsed: unknown = JSON.parse(await readFile(contractPath, 'utf8')); + const validated = validateIrContract(parsed, contractPath, { allowOmittedMetadata: true }); + if (!validated.ok || !validated.contract) { + throw new Error(`Invalid generated contract: ${JSON.stringify(validated.diagnostics)}`); + } + const generator = new CodeGenerator(); + const model = transformIrToTsModel(validated.contract); + model.functions = model.functions.filter(func => !defaultExcludedExports.has(func.name)); + model.classes = model.classes.filter(cls => !defaultExcludedExports.has(cls.name)); + const compiled = compileContract(validated.contract, { + module: model, + generator, + conversion: DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }); + const emittedSource = await readFile(join(outputDir, `${moduleName}.generated.ts`), 'utf8'); + const emittedDeclaration = await readFile( + join(outputDir, `${moduleName}.generated.d.ts`), + 'utf8' + ); + if ( + compiled.generated.typescript !== emittedSource || + compiled.generated.declaration !== emittedDeclaration + ) { + throw new Error('Compiled contract differs from default generated output'); + } + return { + baseline: compiled.generated, + module: compiled.module, + }; +} + +describe.skipIf(!PYTHON_AVAILABLE)('explicit generated client binding prototype', () => { + let temporary = ''; + let generatedDir = ''; + let originalSource = ''; + let originalDeclaration = ''; + let supportsOverloadExtraction = false; + let compiledModule: PythonModule; + let prototype: BindingPrototypeCode; + let clientModule: ClientModule; + let legacyModule: LegacyModule; + + beforeAll(async () => { + const overloadProbe = await processUtils.exec( + pythonPath, + ['-c', 'import typing; print(int(hasattr(typing, "get_overloads")))'], + { timeoutMs: 10_000 } + ); + expect(overloadProbe.code, overloadProbe.stderr).toBe(0); + supportsOverloadExtraction = overloadProbe.stdout.trim() === '1'; + temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-binding-')); + generatedDir = join(temporary, 'generated'); + const generated = await generate({ + pythonModules: { binding_fixture: { runtime: 'node', typeHints: 'strict' } }, + pythonImportPath: [fixtureA], + output: { dir: generatedDir, format: 'esm', declaration: true, sourceMap: false }, + runtime: { node: { pythonPath } }, + performance: { caching: false, batching: false, compression: 'none' }, + }); + expect(generated.failures).toEqual([]); + originalSource = await readFile(join(generatedDir, 'binding_fixture.generated.ts'), 'utf8'); + originalDeclaration = await readFile( + join(generatedDir, 'binding_fixture.generated.d.ts'), + 'utf8' + ); + const compiled = await compiledFixture(generatedDir, 'binding_fixture'); + compiledModule = compiled.module; + expect(compiled.baseline.typescript).toBe(originalSource); + expect(compiled.baseline.declaration).toBe(originalDeclaration); + prototype = renderClientBindingPrototype(compiled.module, new CodeGenerator()); + expect(prototype.declaration).toBe(originalDeclaration); + + const files = [ + ['binding_fixture.generated', prototype.typescript, prototype.declaration], + [ + 'binding_fixture.generated.core', + prototype.bindingPrototype.core.typescript, + prototype.bindingPrototype.core.declaration, + ], + [ + 'binding_fixture.generated.client', + prototype.bindingPrototype.client.typescript, + prototype.bindingPrototype.client.declaration, + ], + ] as const; + for (const [stem, source, declaration] of files) { + await writeFile(join(generatedDir, `${stem}.ts`), source, 'utf8'); + await writeFile(join(generatedDir, `${stem}.d.ts`), declaration, 'utf8'); + const javascript = ts.transpileModule(source, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(join(generatedDir, `${stem}.js`), javascript, 'utf8'); + } + clientModule = (await import( + pathToFileURL(join(generatedDir, 'binding_fixture.generated.client.js')).href + )) as ClientModule; + legacyModule = (await import( + pathToFileURL(join(generatedDir, 'binding_fixture.generated.js')).href + )) as LegacyModule; + }, 60_000); + + afterAll(async () => { + clearRuntimeBridge(); + if (temporary) await rm(temporary, { recursive: true, force: true }); + }); + + it('uses one generated call implementation and keeps default bytes intact', () => { + const core = prototype.bindingPrototype.core.typescript; + const callableCount = (originalSource.match(/getRuntimeBridge\(\)\.call/g) ?? []).length; + expect(callableCount).toBeGreaterThan(0); + expect(core.match(/__tywrapRuntimeProvider\(\)\.call/g)).toHaveLength(callableCount); + expect(prototype.typescript).not.toContain('.call<'); + expect(prototype.bindingPrototype.client.typescript).not.toContain('.call<'); + expect(originalSource).toContain('getRuntimeBridge().call'); + expect(originalDeclaration).toContain('export class Client'); + + const sourceBytes = Buffer.byteLength(originalSource); + const declarationBytes = Buffer.byteLength(originalDeclaration); + const optInSourceBytes = + Buffer.byteLength(prototype.typescript) + + Buffer.byteLength(core) + + Buffer.byteLength(prototype.bindingPrototype.client.typescript); + const optInDeclarationBytes = + Buffer.byteLength(prototype.declaration) + + Buffer.byteLength(prototype.bindingPrototype.core.declaration) + + Buffer.byteLength(prototype.bindingPrototype.client.declaration); + const sourceDeltaPerCallable = (optInSourceBytes - sourceBytes) / callableCount; + expect(sourceDeltaPerCallable).toBeGreaterThan(0); + console.info( + JSON.stringify({ + fixture: 'binding_fixture', + callableCount, + sourceBytes, + declarationBytes, + optInSourceBytes, + optInDeclarationBytes, + sourceDeltaPerCallable, + }) + ); + }); + + it('executes an allocated runtime getter without falling back to the registry', async () => { + const getter = '__tywrapRuntimeProvider1'; + const allocated = renderClientBindingPrototype( + compiledModule, + new CodeGenerator(), + false, + getter + ); + expect(allocated.bindingPrototype.core.typescript).toContain(`${getter}().call`); + expect(allocated.bindingPrototype.core.typescript).not.toContain('getRuntimeBridge().call'); + const allocatedDir = join(temporary, 'allocated'); + await mkdir(allocatedDir); + for (const [stem, source] of [ + ['binding_fixture.generated.core', allocated.bindingPrototype.core.typescript], + ['binding_fixture.generated.client', allocated.bindingPrototype.client.typescript], + ] as const) { + const javascript = ts.transpileModule(source, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(join(allocatedDir, `${stem}.js`), javascript, 'utf8'); + } + const module = (await import( + pathToFileURL(join(allocatedDir, 'binding_fixture.generated.client.js')).href + )) as ClientModule; + const handle = module.bindRuntime(new LabeledRuntime('allocated')); + try { + await expect(handle.api.environment()).resolves.toBe('allocated'); + } finally { + handle.dispose(); + } + }); + + it('rejects source maps until the opt-in files can each carry one', () => { + const generator = new CodeGenerator(); + expect(() => + renderClientBindingPrototype(compiledModule, { + generateModuleDefinition: module => ({ + ...generator.generateModuleDefinition(module), + sourceMap: '{}', + }), + generateModuleBindingTemplate: generator.generateModuleBindingTemplate.bind(generator), + }) + ).toThrow('Client binding prototype does not support source maps'); + }); + + it('keeps two Python environments separate across interleaved and concurrent calls', async () => { + clearRuntimeBridge(); + const bridgeA = new NodeBridge({ + pythonPath, + scriptPath: bridgeScript, + env: { PYTHONPATH: fixtureA }, + }); + const bridgeB = new NodeBridge({ + pythonPath, + scriptPath: bridgeScript, + env: { PYTHONPATH: fixtureB }, + }); + const a = clientModule.bindRuntime(bridgeA); + const b = clientModule.bindRuntime(bridgeB); + try { + expect(() => getRuntimeBridge()).toThrow('No runtime bridge configured'); + expect(await Promise.all([a.api.environment(), b.api.environment()])).toEqual(['A', 'B']); + expect(await a.api.environment()).toBe('A'); + expect(await b.api.environment()).toBe('B'); + expect(await Promise.all([b.api.Client.label('x'), a.api.Client.label('y')])).toEqual([ + 'B:x', + 'A:y', + ]); + expect(await a.api.createClient()).toBe('A-client'); + expect(await a.api.dispose()).toBe('A-dispose'); + expect(await a.api.identity('x')).toBe('x'); + expect(await a.api.select(4)).toBe(4); + expect(await a.api.select('four')).toBe('four'); + expect(await a.api.scale(3)).toBe(3); + expect(await a.api.scale(3, 4)).toBe(12); + expect(await a.api.kwOnly({ label: 'ok' })).toBe('A:ok'); + expect(await a.api.echoBytes(new Uint8Array([1, 2, 3]))).toEqual(new Uint8Array([1, 2, 3])); + + await expect(a.api.invalidReturn()).rejects.toThrow('Return validation failed'); + await expect(a.api.kwOnly()).rejects.toThrow('Missing required keyword-only'); + await expect(a.api.fail()).rejects.toThrow('A-failure'); + await expect(a.api.scale('bad' as never)).rejects.toThrow(); + await expect(b.api.environment()).resolves.toBe('B'); + expect(() => getRuntimeBridge()).toThrow('No runtime bridge configured'); + + const shared = clientModule.bindRuntime(bridgeB); + b.dispose(); + await expect(b.api.environment()).rejects.toBeInstanceOf(BridgeDisposedError); + await expect(shared.api.environment()).resolves.toBe('B'); + expect(bridgeB.isDisposed).toBe(false); + shared.dispose(); + + a.dispose(); + a.dispose(); + await expect(a.api.environment()).rejects.toBeInstanceOf(BridgeDisposedError); + await expect(bridgeA.call('binding_fixture', 'environment', [])).resolves.toBe('A'); + const ownerHandle = clientModule.bindRuntime(bridgeA); + await bridgeA.dispose(); + await expect(ownerHandle.api.environment()).rejects.toBeInstanceOf(BridgeDisposedError); + } finally { + a.dispose(); + b.dispose(); + await Promise.all([bridgeA.dispose(), bridgeB.dispose()]); + } + }, 30_000); + + it('keeps legacy argument, conversion, and return validation on the registry path', async () => { + const bridge = new NodeBridge({ + pythonPath, + scriptPath: bridgeScript, + env: { PYTHONPATH: fixtureA }, + }); + setRuntimeBridge(bridge); + try { + expect(await legacyModule.scale(3, 4)).toBe(12); + expect(await legacyModule.kwOnly({ label: 'ok' })).toBe('A:ok'); + expect(await legacyModule.echoBytes(new Uint8Array([4, 5]))).toEqual(new Uint8Array([4, 5])); + await expect(legacyModule.kwOnly()).rejects.toThrow('Missing required keyword-only'); + await expect(legacyModule.invalidReturn()).rejects.toThrow('Return validation failed'); + expect(await legacyModule.Client.label('x')).toBe('A:x'); + } finally { + clearRuntimeBridge(); + await bridge.dispose(); + } + }, 30_000); + + it('keeps a call started before handle disposal on its selected bridge', async () => { + let release!: () => void; + const gate = new Promise(resolve => { + release = resolve; + }); + const runtime: RuntimeExecution = { + async call(): Promise { + await gate; + return 'ready' as T; + }, + async dispose(): Promise {}, + }; + const handle = clientModule.bindRuntime(runtime); + const started = handle.api.environment(); + handle.dispose(); + release(); + await expect(started).resolves.toBe('ready'); + await expect(handle.api.environment()).rejects.toBeInstanceOf(BridgeDisposedError); + }); + + it('uses the same companion with Node and HTTP bridges', async () => { + const server = createServer((request, response) => { + request.resume(); + response.setHeader('content-type', 'application/json'); + response.end(JSON.stringify({ id: 1, result: 'H' })); + }); + await new Promise(resolveServer => server.listen(0, '127.0.0.1', resolveServer)); + const address = server.address() as AddressInfo; + const node = new NodeBridge({ + pythonPath, + scriptPath: bridgeScript, + env: { PYTHONPATH: fixtureA }, + }); + const http = new HttpBridge({ baseURL: `http://127.0.0.1:${address.port}` }); + try { + const a = clientModule.bindRuntime(node); + const h = clientModule.bindRuntime(http); + expect(await Promise.all([a.api.environment(), h.api.environment()])).toEqual(['A', 'H']); + } finally { + await Promise.all([node.dispose(), http.dispose()]); + await new Promise(resolveServer => server.close(() => resolveServer())); + } + }, 30_000); + + it('keeps bound and legacy behavior explicit across successful and failed reloads', async () => { + let nextLabel = 'A'; + const reloader = await createBridgeReloader(async () => { + if (nextLabel === 'fail') throw new Error('reload failed'); + return new LabeledRuntime(nextLabel); + }); + try { + const oldBridge = reloader.current(); + const oldHandle = clientModule.bindRuntime(oldBridge); + expect(await oldHandle.api.environment()).toBe('A'); + expect(await legacyModule.environment()).toBe('A'); + + nextLabel = 'B'; + await reloader.reload(); + const newHandle = clientModule.bindRuntime(reloader.current()); + await vi.waitFor(() => expect(oldBridge.disposed).toBe(true)); + await expect(oldHandle.api.environment()).rejects.toBeInstanceOf(BridgeDisposedError); + expect(await newHandle.api.environment()).toBe('B'); + expect(await legacyModule.environment()).toBe('B'); + + nextLabel = 'fail'; + await expect(reloader.reload()).rejects.toThrow('reload failed'); + expect(reloader.current().label).toBe('B'); + expect(await newHandle.api.environment()).toBe('B'); + expect(await legacyModule.environment()).toBe('B'); + } finally { + await reloader.dispose(); + clearRuntimeBridge(); + } + }); + + it('typechecks overloads, generic inputs, optional arguments, and class calls', async () => { + const consumer = join(generatedDir, 'binding-consumer.ts'); + const selectSignatures = (originalDeclaration.match(/^export function select\(/gm) ?? []) + .length; + expect(selectSignatures).toBe(supportsOverloadExtraction ? 2 : 1); + const selectChecks = supportsOverloadExtraction + ? `const b: Promise = client.api.select(2); +const c: Promise = client.api.select('x'); +// @ts-expect-error the string overload returns a string +const wrong: Promise = client.api.select('x'); +void wrong;` + : `const b: Promise = client.api.select(2); +const c: Promise = client.api.select('x');`; + await writeFile( + consumer, + `import { bindRuntime, type BoundRuntime } from './binding_fixture.generated.client.js'; +import { identity as legacyIdentity } from './binding_fixture.generated.js'; +declare const runtime: BoundRuntime; +const client = bindRuntime(runtime); +const callOnly = bindRuntime({ call: async () => undefined as T }); +const a: Promise = client.api.identity('x'); +const legacyA: Promise = legacyIdentity('x'); +// @ts-expect-error the explicit generic input type is string +client.api.identity(3); +// @ts-expect-error an unresolved type variable cannot promise a string result +const unsafeResult: Promise = client.api.identity('x'); +// @ts-expect-error legacy calls use the same unresolved return contract +const unsafeLegacy: Promise = legacyIdentity('x'); +${selectChecks} +const d: Promise = client.api.scale(2); +const e: Promise = client.api.scale(2, 3); +const f: Promise = client.api.Client.label('x'); +const g: Promise = client.api.kwOnly({ label: 'x' }); +const h: Promise = client.api.echoBytes(new Uint8Array([1])); +void [callOnly, a, legacyA, unsafeResult, unsafeLegacy, b, c, d, e, f, g, h]; +`, + 'utf8' + ); + const tscPath = join(process.cwd(), 'node_modules', 'typescript', 'lib', 'tsc.js'); + const compiled = await processUtils.exec( + process.execPath, + [ + tscPath, + '--ignoreConfig', + '--noEmit', + '--pretty', + 'false', + '--strict', + '--target', + 'ES2022', + '--lib', + 'ES2022,DOM,DOM.Iterable', + '--module', + 'NodeNext', + '--moduleResolution', + 'NodeNext', + '--skipLibCheck', + consumer, + ], + { cwd: process.cwd(), timeoutMs: 30_000 } + ); + expect(compiled.code, compiled.stdout || compiled.stderr).toBe(0); + }, 30_000); + + it('records source and declaration size for a representative module', async () => { + const comparisonDir = await mkdtemp(join(process.cwd(), 'test', '.tywrap-binding-size-')); + try { + const result = await generate({ + pythonModules: { advanced_types: { runtime: 'node', typeHints: 'strict' } }, + pythonImportPath: [resolve('test/fixtures/python')], + output: { dir: comparisonDir, format: 'esm', declaration: true, sourceMap: false }, + runtime: { node: { pythonPath } }, + performance: { caching: false, batching: false, compression: 'none' }, + }); + expect(result.failures).toEqual([]); + const compiled = await compiledFixture(comparisonDir, 'advanced_types'); + const source = compiled.baseline.typescript; + const declaration = compiled.baseline.declaration; + const rendered = renderClientBindingPrototype(compiled.module, new CodeGenerator()); + const callableCount = (source.match(/getRuntimeBridge\(\)\.call/g) ?? []).length; + expect(callableCount).toBeGreaterThan(0); + const sourceBytes = Buffer.byteLength(source); + const declarationBytes = Buffer.byteLength(declaration); + const optInSourceBytes = + Buffer.byteLength(rendered.typescript) + + Buffer.byteLength(rendered.bindingPrototype.core.typescript) + + Buffer.byteLength(rendered.bindingPrototype.client.typescript); + const optInDeclarationBytes = + Buffer.byteLength(rendered.declaration) + + Buffer.byteLength(rendered.bindingPrototype.core.declaration) + + Buffer.byteLength(rendered.bindingPrototype.client.declaration); + console.info( + JSON.stringify({ + fixture: 'advanced_types', + callableCount, + sourceBytes, + declarationBytes, + optInSourceBytes, + optInDeclarationBytes, + sourceDeltaPerCallable: (optInSourceBytes - sourceBytes) / callableCount, + }) + ); + } finally { + await rm(comparisonDir, { recursive: true, force: true }); + } + }, 60_000); +}); diff --git a/test/data-plane-perf.test.ts b/test/data-plane-perf.test.ts index e1f836dc..a128c30a 100644 --- a/test/data-plane-perf.test.ts +++ b/test/data-plane-perf.test.ts @@ -16,10 +16,8 @@ * Apple-Silicon numbers in docs/perf-baselines.md (which are indicative * only and machine-dependent). CI baselines are stored/compared separately * from the local doc. - * - chunk overhead vs a same-run HIGH-CEILING single-frame median: bounded - * by a CALIBRATED ratio (the plan's "~2.0x" strawman; the actual, - * inherent fragmentation cost on this machine is ~3.0x — see - * CHUNK_OVERHEAD_MAX_RATIO for the calibration rationale) + * - chunk overhead vs a same-run high-ceiling single-frame median: + * bounded by the existing 3.5x ratio (see CHUNK_OVERHEAD_MAX_RATIO) * - small-call PooledTransport throughput: >= ~70% of a same-run baseline * - existing Arrow ndarray/DataFrame + 100k-decode benches: <= ~2.0x of a * same-run warm baseline @@ -84,18 +82,10 @@ const RUNTIME_DIR = resolve(process.cwd(), 'runtime'); // process, NOT absolute numbers — deliberately generous to absorb CI noise // while still catching order-of-magnitude regressions. // -// CHUNK_OVERHEAD_MAX_RATIO is CALIBRATED, not the plan's strawman "~2.0x". On -// this machine the chunked-vs-single-frame median ratio is a stable ~2.9-3.0x. -// That overhead is INHERENT to fragmentation, not a regression: a 20 MiB -// response splits into ~20 frames, each a separate json.dumps + stdout flush on -// the Python side and a separate JSON.parse on the TS side (~20x the per-line -// work vs one big line), PLUS the spec-mandated full-payload integrity re-passes -// the reassembler must run (exact byte-count check + strict UTF-8 re-decode, -// frame-codec.ts:337/349). None of that is avoidable without weakening the -// framing contract. The budget is set at 3.5x: comfortably above the observed -// ~3.0x (CI-noise headroom) yet far below the >=10x an accidental O(n^2) -// reassembly would produce — which is the regression class this gate exists to -// catch. (Plan #233 wrote the figure as "~1.8-2.0x"; the tilde means calibrate.) +// Keep the existing 3.5x budget for this change. A chunked response needs +// separate frame encoding, stdout flushes, and parsing. Reassembly checks its +// byte count and UTF-8. GitHub runner measurements vary, so one passing run +// does not establish a stable ratio after the Python ASCII fast path. const CHUNK_OVERHEAD_MAX_RATIO = 3.5; // chunked median <= 3.5x single-frame median (calibrated) const POOL_THROUGHPUT_MIN_RATIO = 0.7; // pooled throughput >= 70% of baseline const ARROW_BENCH_MAX_RATIO = 2.0; // warm Arrow bench median <= 2.0x baseline diff --git a/test/decoded_provenance.test.ts b/test/decoded_provenance.test.ts new file mode 100644 index 00000000..55f756ef --- /dev/null +++ b/test/decoded_provenance.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest'; +import { DecodedProvenance } from '../src/runtime/decoded-provenance.js'; + +describe('decoded provenance', () => { + it('keeps equal scalar values separate by call and nested location', () => { + const firstParent = { one: 1.5, two: 1.5 }; + const secondParent = { one: 1.5 }; + const first = new DecodedProvenance(); + const second = new DecodedProvenance(); + + first.recordChild(firstParent, 'one', { marker: 'ndarray', dims: 0, dtype: 'float16' }); + first.recordChild(firstParent, 'two', { marker: 'ndarray', dims: 0, dtype: 'float32' }); + second.recordChild(secondParent, 'one', { marker: 'ndarray', dims: 0, dtype: 'float64' }); + + expect(first.atChild(firstParent, 'one')?.dtype).toBe('float16'); + expect(first.atChild(firstParent, 'two')?.dtype).toBe('float32'); + expect(first.atChild(secondParent, 'one')).toBeUndefined(); + expect(second.atChild(firstParent, 'one')).toBeUndefined(); + expect(second.atChild(secondParent, 'one')?.dtype).toBe('float64'); + }); + + it('uses the same array slot for a numeric or string index', () => { + const parent = [1.5]; + const provenance = new DecodedProvenance(); + const metadata = { marker: 'ndarray' as const, dims: 0, dtype: 'float16' }; + provenance.recordChild(parent, 0, metadata); + expect(provenance.atChild(parent, '0')).toEqual(metadata); + expect(() => provenance.recordChild(parent, '0', metadata)).toThrow(/Duplicate child/); + }); + + it('has one root slot and a bounded number of entries', () => { + const evidence = { marker: 'ndarray' as const, dims: 0, dtype: 'float16' }; + const provenance = new DecodedProvenance(2); + const parent = [1.5]; + provenance.recordRoot(evidence); + provenance.recordChild(parent, 0, evidence); + + expect(provenance.atRoot()).toEqual(evidence); + expect(provenance.atChild(parent, 0)).toEqual(evidence); + expect(() => provenance.recordRoot(evidence)).toThrow(/Duplicate root/); + expect(() => provenance.recordChild(parent, 0, evidence)).toThrow(/Duplicate child/); + expect(() => provenance.recordChild(parent, 1, evidence)).toThrow(/exceeds 2 entries/); + }); +}); diff --git a/test/dev.test.ts b/test/dev.test.ts index f672340e..7021cbb6 100644 --- a/test/dev.test.ts +++ b/test/dev.test.ts @@ -375,6 +375,63 @@ describeNodeOnly('startNodeWatchSession', () => { } }, 30000); + it('keeps the last good bridge when source changes during bridge preparation', async () => { + const tempDir = await mkdtemp(join(process.cwd(), '.tmp-tywrap-dev-mid-reload-')); + const packageDir = join(tempDir, 'watchpkg'); + const outputDir = join(tempDir, 'generated'); + const configPath = join(tempDir, 'tywrap.config.json'); + const pythonPath = getDefaultPythonPath(); + const events: NodeWatchEvent[] = []; + let changeSourceBeforeNextBridge = false; + + await mkdir(packageDir, { recursive: true }); + await writePythonModule(packageDir, 'def answer() -> int:\n return 1\n'); + await writeFile( + configPath, + JSON.stringify({ + pythonModules: { watchpkg: { runtime: 'node', typeHints: 'strict' } }, + pythonImportPath: [tempDir], + output: { dir: outputDir, format: 'esm', declaration: false, sourceMap: false }, + runtime: { node: { pythonPath } }, + performance: { caching: false, batching: false, compression: 'none' }, + }), + 'utf-8' + ); + + let session: NodeWatchSession | undefined; + try { + session = await startNodeWatchSession({ + configFile: configPath, + createBridge: async () => { + if (changeSourceBeforeNextBridge) { + changeSourceBeforeNextBridge = false; + await writePythonModule(packageDir, 'def answer() -> int \n return 9\n'); + } + return new SnapshotPythonBridge(join(packageDir, '__init__.py'), pythonPath); + }, + onEvent: event => events.push(event), + }); + + const generatedModule = (await import( + pathToFileURL(join(outputDir, 'watchpkg.generated.ts')).href + )) as { answer: () => Promise }; + expect(await generatedModule.answer()).toBe(1); + + changeSourceBeforeNextBridge = true; + await expect(session.reloadNow()).resolves.toBe(false); + const reloadError = events.find(event => event.type === 'reload-error' && event.manual); + expect(reloadError).toMatchObject({ + error: { + message: 'Watched Python source changed during reload; keeping the current bridge', + }, + }); + expect(await generatedModule.answer()).toBe(1); + } finally { + await session?.close(); + await rm(tempDir, { recursive: true, force: true }); + } + }, 30000); + it('passes the latest resolved config into createBridge on manual reloads', async () => { const tempDir = await mkdtemp(join(process.cwd(), '.tmp-tywrap-dev-config-bridge-')); const packageDir = join(tempDir, 'configpkg'); diff --git a/test/fixtures/architecture-overload.typecheck.ts.txt b/test/fixtures/architecture-overload.typecheck.ts.txt new file mode 100644 index 00000000..7581b02a --- /dev/null +++ b/test/fixtures/architecture-overload.typecheck.ts.txt @@ -0,0 +1,33 @@ +import { selectRecord } from './generated/architecture_callable_fixture.generated.js'; +import { float16Values } from './generated/consumer_fixture.generated.js'; + +type Float16Value = number | Float16Value[]; +type GeneratedFloat16Value = Awaited>; + +const float16Result: Promise = float16Values(); +const acceptsScalar: number extends GeneratedFloat16Value ? true : never = true; +const acceptsArray: number[] extends GeneratedFloat16Value ? true : never = true; + +// @ts-expect-error A decoded float16 array is not a string. +const wrongFloat16Result: Promise = float16Values(); + +const textRecord: Promise>> = selectRecord('label'); +const integerRecord: Promise>> = selectRecord(42); + +// @ts-expect-error An integer input must not infer a string record. +const wrongTextRecord: Promise>> = selectRecord(42); + +// @ts-expect-error A string input must not infer an integer record. +const wrongIntegerRecord: Promise>> = selectRecord('label'); + +// @ts-expect-error A boolean input matches no overload. +selectRecord(true); + +void textRecord; +void integerRecord; +void wrongTextRecord; +void wrongIntegerRecord; +void float16Result; +void wrongFloat16Result; +void acceptsScalar; +void acceptsArray; diff --git a/test/fixtures/architecture-value-cases.v1.json b/test/fixtures/architecture-value-cases.v1.json new file mode 100644 index 00000000..ff610f07 --- /dev/null +++ b/test/fixtures/architecture-value-cases.v1.json @@ -0,0 +1,67 @@ +{ + "schemaVersion": 1, + "contractRevision": 2, + "propertySeed": 20260920, + "safeIntegers": [ + { "decimal": "-9007199254740991", "accepted": true }, + { "decimal": "9007199254740991", "accepted": true }, + { "decimal": "-9007199254740992", "accepted": false }, + { "decimal": "9007199254740992", "accepted": false }, + { "decimal": "9007199254740993", "accepted": false }, + { "decimal": "-9223372036854775808", "accepted": false }, + { "decimal": "9223372036854775807", "accepted": false }, + { "decimal": "265252859812191058636308480000000", "accepted": false } + ], + "binary16": [ + { "wordHex": "0000", "decimal": "0", "negativeZero": false }, + { "wordHex": "8000", "decimal": "-0", "negativeZero": true }, + { "wordHex": "0001", "decimal": "5.960464477539063e-8", "negativeZero": false }, + { "wordHex": "03ff", "decimal": "0.00006097555160522461", "negativeZero": false }, + { "wordHex": "0400", "decimal": "0.00006103515625", "negativeZero": false }, + { "wordHex": "3e00", "decimal": "1.5", "negativeZero": false }, + { "wordHex": "c080", "decimal": "-2.25", "negativeZero": false }, + { "wordHex": "7bff", "decimal": "65504", "negativeZero": false }, + { "wordHex": "fbff", "decimal": "-65504", "negativeZero": false } + ], + "nonFiniteBinary16": [ + { "wordHex": "7c00", "kind": "infinity" }, + { "wordHex": "fc00", "kind": "infinity" }, + { "wordHex": "7d00", "kind": "nan" }, + { "wordHex": "7e00", "kind": "nan" }, + { "wordHex": "fe00", "kind": "nan" } + ], + "nestedCases": [ + { + "path": "result.outer[0].value", + "value": "9007199254740993", + "outcome": "reject" + }, + { + "path": "result.outer[0].tensor.value", + "float16Words": ["3e00", "c080"], + "outcome": "numbers" + } + ], + "overloadCases": [ + { + "function": "select_record", + "inputType": "str", + "argument": "label", + "returnType": "dict[str, dict[str, str]]", + "expected": { "outer": { "value": "label" } } + }, + { + "function": "select_record", + "inputType": "int", + "argument": 42, + "returnType": "dict[str, dict[str, int]]", + "expected": { "outer": { "value": 42 } } + } + ], + "wrongReturn": { + "function": "wrong_integer_return", + "declaredType": "int", + "returnedValue": "not an integer", + "expectedError": "BridgeValidationError" + } +} diff --git a/test/fixtures/architecture_callable_fixture.py b/test/fixtures/architecture_callable_fixture.py new file mode 100644 index 00000000..d600eb5a --- /dev/null +++ b/test/fixtures/architecture_callable_fixture.py @@ -0,0 +1,35 @@ +"""Controlled overload and return-validation cases for the clean consumer.""" + +from __future__ import annotations + +import typing + + +@typing.overload +def select_record(key: str) -> dict[str, dict[str, str]]: ... + + +@typing.overload +def select_record(key: int) -> dict[str, dict[str, int]]: ... + + +def select_record(key: str | int) -> dict[str, dict[str, str | int]]: + return {'outer': {'value': key}} + + +@typing.overload +def select_record_wrong(key: str) -> dict[str, dict[str, str]]: ... + + +@typing.overload +def select_record_wrong(key: int) -> dict[str, dict[str, int]]: ... + + +def select_record_wrong(key: str | int) -> dict[str, dict[str, str | int]]: + if isinstance(key, str): + return {'outer': {'value': 42}} + return {'outer': {'value': 'not an integer'}} + + +def wrong_integer_return() -> int: + return 'not an integer' diff --git a/test/fixtures/python/async_module.py b/test/fixtures/python/async_module.py index 9f3d348f..2a2bb248 100644 --- a/test/fixtures/python/async_module.py +++ b/test/fixtures/python/async_module.py @@ -19,6 +19,16 @@ async def process_items(items: List[str]) -> List[str]: return results +async def delayed_value(delay: float) -> str: + await asyncio.sleep(delay) + return "finished" + + +async def raise_after_await() -> str: + await asyncio.sleep(0) + raise ValueError("async failure") + + async def async_generator(count: int) -> AsyncIterator[int]: """Async generator yielding numbers.""" for i in range(count): diff --git a/test/fixtures/python/binding_a/binding_fixture.py b/test/fixtures/python/binding_a/binding_fixture.py new file mode 100644 index 00000000..23097351 --- /dev/null +++ b/test/fixtures/python/binding_a/binding_fixture.py @@ -0,0 +1,62 @@ +"""First Python environment for explicit client binding tests.""" + +from __future__ import annotations + +from typing import TypeVar, overload + + +T = TypeVar("T") + + +def environment() -> str: + return "A" + + +def create_client() -> str: + return "A-client" + + +def dispose() -> str: + return "A-dispose" + + +def identity(value: T) -> T: + return value + + +@overload +def select(value: int) -> int: ... + + +@overload +def select(value: str) -> str: ... + + +def select(value: int | str) -> int | str: + return value + + +def scale(value: int, factor: int = 1) -> int: + return value * factor + + +def kw_only(*, label: str) -> str: + return f"A:{label}" + + +def echo_bytes(value: bytes) -> bytes: + return value + + +def invalid_return() -> int: + return "wrong" # type: ignore[return-value] + + +def fail() -> str: + raise RuntimeError("A-failure") + + +class Client: + @classmethod + def label(cls, value: str) -> str: + return f"A:{value}" diff --git a/test/fixtures/python/binding_b/binding_fixture.py b/test/fixtures/python/binding_b/binding_fixture.py new file mode 100644 index 00000000..7d0410a9 --- /dev/null +++ b/test/fixtures/python/binding_b/binding_fixture.py @@ -0,0 +1,62 @@ +"""Second Python environment for explicit client binding tests.""" + +from __future__ import annotations + +from typing import TypeVar, overload + + +T = TypeVar("T") + + +def environment() -> str: + return "B" + + +def create_client() -> str: + return "B-client" + + +def dispose() -> str: + return "B-dispose" + + +def identity(value: T) -> T: + return value + + +@overload +def select(value: int) -> int: ... + + +@overload +def select(value: str) -> str: ... + + +def select(value: int | str) -> int | str: + return value + + +def scale(value: int, factor: int = 1) -> int: + return value * factor + + +def kw_only(*, label: str) -> str: + return f"B:{label}" + + +def echo_bytes(value: bytes) -> bytes: + return value + + +def invalid_return() -> int: + return "wrong" # type: ignore[return-value] + + +def fail() -> str: + raise RuntimeError("B-failure") + + +class Client: + @classmethod + def label(cls, value: str) -> str: + return f"B:{value}" diff --git a/test/fixtures/python/ignore_sigterm_bridge.py b/test/fixtures/python/ignore_sigterm_bridge.py new file mode 100644 index 00000000..cab3139b --- /dev/null +++ b/test/fixtures/python/ignore_sigterm_bridge.py @@ -0,0 +1,10 @@ +import signal +import sys +import time + + +signal.signal(signal.SIGTERM, signal.SIG_IGN) +print('READY', file=sys.stderr, flush=True) +sys.stdin.readline() +while True: + time.sleep(0.1) diff --git a/test/fixtures/python/positional_overloads.py b/test/fixtures/python/positional_overloads.py new file mode 100644 index 00000000..a5fee072 --- /dev/null +++ b/test/fixtures/python/positional_overloads.py @@ -0,0 +1,18 @@ +"""Overloads with positional-only and keyword-only parameters.""" + +from typing import overload as _overload + + +@_overload +def choose(value: str, /, bias: int = 0, *, loud: bool = False) -> str: ... + + +@_overload +def choose(value: int, /, bias: int = 0, *, loud: bool = False) -> int: ... + + +def choose(value: str | int, /, bias: int = 0, *, loud: bool = False) -> str | int: + if isinstance(value, str): + result = value + "!" * bias + return result.upper() if loud else result + return value + bias diff --git a/test/fixtures/python/value_contract_exact_integer.py b/test/fixtures/python/value_contract_exact_integer.py new file mode 100644 index 00000000..b9a2d431 --- /dev/null +++ b/test/fixtures/python/value_contract_exact_integer.py @@ -0,0 +1,14 @@ +"""Importable exact-integer fixture for the bounded v3 compiler proof.""" + +import math + + +def combine_exact(value: int, nested: list[int], flag: bool, ratio: float) -> int: + """Combine scalar and nested integers after the bridge decodes them.""" + total = value + sum(nested) + return total if flag and math.copysign(1.0, ratio) > 0 else -total + + +def echo_exact(value: int, nested: list[int]) -> list[list[int]]: + """Return nested values after the bridge decodes them.""" + return [[value], nested, [-value]] diff --git a/test/fixtures/python/value_contract_point.py b/test/fixtures/python/value_contract_point.py new file mode 100644 index 00000000..6e3b4559 --- /dev/null +++ b/test/fixtures/python/value_contract_point.py @@ -0,0 +1,14 @@ +"""Importable Point fixture for the dataclass value proof.""" + +from dataclasses import dataclass + + +@dataclass +class Point: + x: int + y: int = 2 + + +def make_point() -> Point: + """Return a Point with its defaulted field present.""" + return Point(1) diff --git a/test/generator.test.ts b/test/generator.test.ts index e23e4dfd..39082e73 100644 --- a/test/generator.test.ts +++ b/test/generator.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from 'vitest'; import { CodeGenerator } from '../src/core/generator.js'; +import type { Parameter, PythonFunction, PythonModule, PythonType } from '../src/types/index.js'; describe('CodeGenerator', () => { const gen = new CodeGenerator(); @@ -59,6 +60,76 @@ describe('CodeGenerator', () => { expect(code.typescript).toContain('createReturnValidator'); }); + it('uses one opt-in runtime provider for free and static wrappers', () => { + const ping = { + name: 'ping', + signature: { + parameters: [], + returnType: { kind: 'primitive', name: 'int' }, + isAsync: false, + isGenerator: false, + }, + decorators: [], + isAsync: false, + isGenerator: false, + returnType: { kind: 'primitive', name: 'int' }, + parameters: [], + } satisfies PythonFunction; + const module = { + name: 'binding_fixture', + functions: [ping], + classes: [ + { + name: 'Box', + kind: 'class', + bases: [], + properties: [], + decorators: [], + methods: [{ ...ping, name: 'pong', methodKind: 'static' }], + }, + ], + typeAliases: [], + imports: [], + exports: [], + } satisfies PythonModule; + const normal = gen.generateModuleDefinition(module); + const bound = gen.generateModuleBindingTemplate(module); + expect(normal.typescript).toContain( + "getRuntimeBridge().call('binding_fixture', 'ping'" + ); + expect(normal.typescript).toContain( + "getRuntimeBridge().call('binding_fixture', 'Box.pong'" + ); + expect(bound.typescript).toContain( + "__tywrapRuntimeProvider().call('binding_fixture', 'ping'" + ); + expect(bound.typescript).toContain( + "__tywrapRuntimeProvider().call('binding_fixture', 'Box.pong'" + ); + expect(bound.typescript).not.toContain('getRuntimeBridge'); + expect(bound.declaration).toBe(normal.declaration); + for (const identifier of [ + 'ping', + 'provider', + 'createReturnValidator', + '__tywrapReturnDefinitions', + '__args', + 'for', + 'super', + 'this', + 'arguments', + 'undefined', + 'provider;inject', + ]) { + expect(() => gen.generateModuleBindingTemplate(module, false, identifier)).toThrow( + /Invalid runtime getter identifier/ + ); + } + expect( + gen.generateModuleBindingTemplate(module, false, '__tywrapRuntimeProvider1').typescript + ).toContain('__tywrapRuntimeProvider1().call'); + }); + it('emits a null union member for X | None returns, not an accept-everything any', () => { const code = gen.generateFunctionWrapper( { @@ -225,14 +296,13 @@ describe('CodeGenerator', () => { }); it('degrades iterator-protocol returns to unknown with a no-op validator', () => { - // A generator/iterator object can never cross the bridge (serialization - // rejects it loudly), so Generator<...> as a return type could never - // carry a value. + // The serializer rejects generator and iterator objects. + // The wrapper cannot return a Generator value. const degraded: string[] = []; const honestGenerator = new CodeGenerator(undefined, { onTypeDegrade: typeName => degraded.push(typeName), }); - const returnType = { + const returnType: PythonType = { kind: 'generic', name: 'Generator', module: 'typing', @@ -267,12 +337,12 @@ describe('CodeGenerator', () => { expect(degraded).toEqual(['typing.Generator']); }); - it('keeps Iterable returns as arrays — a decoded list satisfies them honestly', () => { + it('keeps Iterable returns as decoded arrays', () => { const degraded: string[] = []; const honestGenerator = new CodeGenerator(undefined, { onTypeDegrade: typeName => degraded.push(typeName), }); - const returnType = { + const returnType: PythonType = { kind: 'generic', name: 'Iterable', module: 'typing', @@ -561,6 +631,153 @@ describe('CodeGenerator', () => { ); }); + it('preserves declared overload input-to-return relationships', () => { + const code = gen.generateFunctionWrapper( + { + name: 'get_value', + signature: { + parameters: [ + { + name: 'key', + type: { + kind: 'union', + types: [ + { kind: 'primitive', name: 'str' }, + { kind: 'primitive', name: 'int' }, + ], + }, + optional: false, + varArgs: false, + kwArgs: false, + }, + ], + returnType: { + kind: 'union', + types: [ + { kind: 'primitive', name: 'str' }, + { kind: 'primitive', name: 'int' }, + ], + }, + isAsync: false, + isGenerator: false, + }, + decorators: [], + isAsync: false, + isGenerator: false, + returnType: { + kind: 'union', + types: [ + { kind: 'primitive', name: 'str' }, + { kind: 'primitive', name: 'int' }, + ], + }, + parameters: [ + { + name: 'key', + type: { + kind: 'union', + types: [ + { kind: 'primitive', name: 'str' }, + { kind: 'primitive', name: 'int' }, + ], + }, + optional: false, + varArgs: false, + kwArgs: false, + }, + ], + overloads: [ + { + parameters: [ + { + name: 'key', + type: { kind: 'primitive', name: 'str' }, + optional: false, + varArgs: false, + kwArgs: false, + }, + ], + returnType: { kind: 'primitive', name: 'str' }, + }, + { + parameters: [ + { + name: 'key', + type: { kind: 'primitive', name: 'int' }, + optional: false, + varArgs: false, + kwArgs: false, + }, + ], + returnType: { kind: 'primitive', name: 'int' }, + }, + ], + } satisfies PythonFunction, + 'advanced_types' + ); + + expect(code.typescript).toContain('export function getValue(key: string): Promise;'); + expect(code.typescript).toContain('export function getValue(key: number): Promise;'); + expect(code.typescript).toContain( + 'export async function getValue(key: unknown): Promise' + ); + expect(code.declaration).toContain('export function getValue(key: string): Promise;'); + expect(code.declaration).toContain('export function getValue(key: number): Promise;'); + }); + + it('does not expose the implementation signature beside declared overloads', () => { + const key: Parameter = { + name: 'key', + type: { kind: 'primitive', name: 'str' }, + optional: false, + varArgs: false, + kwArgs: false, + }; + const fallback: Parameter = { + name: 'fallback', + type: { kind: 'primitive', name: 'int' }, + optional: true, + varArgs: false, + kwArgs: false, + }; + const method = { + name: 'get_value', + signature: { + parameters: [key, fallback], + returnType: { kind: 'primitive', name: 'str' }, + isAsync: false, + isGenerator: false, + }, + decorators: [], + isAsync: false, + isGenerator: false, + parameters: [key, fallback], + returnType: { kind: 'primitive', name: 'str' }, + methodKind: 'static', + overloads: [{ parameters: [key], returnType: { kind: 'primitive', name: 'str' } }], + } satisfies PythonFunction; + + const functionCode = gen.generateFunctionWrapper(method, 'fixture'); + expect(functionCode.declaration).toContain( + 'export function getValue(key: string): Promise;' + ); + expect(functionCode.declaration).not.toContain('fallback'); + + const classCode = gen.generateClassWrapper( + { + name: 'Catalog', + bases: [], + methods: [method], + properties: [], + decorators: [], + kind: 'class', + }, + 'fixture' + ); + expect(classCode.declaration).toContain('static getValue(key: string): Promise;'); + expect(classCode.declaration).not.toContain('fallback'); + }); + it('models *args as an array parameter when kwargs are present', () => { const code = gen.generateFunctionWrapper( { diff --git a/test/integration.test.ts b/test/integration.test.ts index 659f67c2..e97d85e6 100644 --- a/test/integration.test.ts +++ b/test/integration.test.ts @@ -224,6 +224,78 @@ describe('IR-only integration', () => { { cwd: process.cwd(), timeoutMs: 30_000 } ); + expect(compile.code, `${compile.stdout}\n${compile.stderr}`).toBe(0); + expect(compile.stderr).toBe(''); + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }, 30_000); + + it('preserves Python overload input-to-return relationships in generated declarations', async () => { + const support = await processUtils.exec(defaultPythonPath, [ + '-c', + 'import typing; raise SystemExit(0 if hasattr(typing, "get_overloads") else 1)', + ]); + if (support.code !== 0) { + return; + } + const tempDir = await mkdtemp(join(process.cwd(), 'test', '.tywrap-overload-contract-')); + try { + const outDir = join(tempDir, 'generated'); + const result = await generate({ + pythonModules: { advanced_types: { runtime: 'node', typeHints: 'strict' } }, + pythonImportPath: ['test/fixtures/python'], + output: { dir: outDir, format: 'esm', declaration: true, sourceMap: false }, + runtime: { node: { pythonPath: defaultPythonPath } }, + performance: { caching: false, batching: false, compression: 'none' }, + } as any); + + expect(result.failures).toEqual([]); + const generated = await fsUtils.readFile(join(outDir, 'advanced_types.generated.d.ts')); + expect(generated).toContain('export function getValue(key: string): Promise;'); + expect(generated).toContain('export function getValue(key: number): Promise;'); + + const consumerPath = join(tempDir, 'consumer.ts'); + await writeFile( + consumerPath, + `import { getValue } from './generated/advanced_types.generated.js'; + +const text: Promise = getValue('key'); +const integer: Promise = getValue(1); +// @ts-expect-error boolean has no declared Python overload +void getValue(true); +// @ts-expect-error string overload cannot return Promise +const wrong: Promise = getValue('key'); + +void text; +void integer; +void wrong; +`, + 'utf8' + ); + const tscPath = join(process.cwd(), 'node_modules', 'typescript', 'lib', 'tsc.js'); + const compile = await processUtils.exec( + process.execPath, + [ + tscPath, + '--ignoreConfig', + '--noEmit', + '--pretty', + 'false', + '--target', + 'ES2022', + '--lib', + 'ES2022,DOM,DOM.Iterable', + '--module', + 'ESNext', + '--moduleResolution', + 'bundler', + '--skipLibCheck', + consumerPath, + ], + { cwd: process.cwd(), timeoutMs: 30_000 } + ); + expect(compile.code).toBe(0); expect(compile.stderr).toBe(''); } finally { @@ -231,6 +303,90 @@ describe('IR-only integration', () => { } }, 30_000); + it('preserves type variables declared only by overload signatures', async () => { + const support = await processUtils.exec(defaultPythonPath, [ + '-c', + 'import typing; raise SystemExit(0 if hasattr(typing, "get_overloads") else 1)', + ]); + if (support.code !== 0) { + return; + } + const tempDir = await mkdtemp(join(process.cwd(), 'test', '.tywrap-generic-overload-')); + try { + const importDir = join(tempDir, 'py'); + await mkdir(importDir, { recursive: true }); + await writeFile( + join(importDir, 'generic_overload.py'), + `from typing import TypeVar, overload + +T = TypeVar("T") + +@overload +def choose(value: T) -> T: ... + +@overload +def choose(value: None) -> None: ... + +def choose(value: object) -> object: + return value +`, + 'utf8' + ); + const outDir = join(tempDir, 'generated'); + const result = await generate({ + pythonModules: { generic_overload: { runtime: 'node', typeHints: 'strict' } }, + pythonImportPath: [importDir], + output: { dir: outDir, format: 'esm', declaration: true, sourceMap: false }, + runtime: { node: { pythonPath: defaultPythonPath } }, + performance: { caching: false, batching: false, compression: 'none' }, + } as any); + expect(result.failures).toEqual([]); + const declaration = await fsUtils.readFile(join(outDir, 'generic_overload.generated.d.ts')); + expect(declaration).toContain('export function choose(value: T): Promise;'); + const consumerPath = join(tempDir, 'consumer.ts'); + await writeFile( + consumerPath, + `import { choose } from './generated/generic_overload.generated.js'; + +const text: Promise = choose('key'); +const integer: Promise = choose(2); +// @ts-expect-error An unresolved TypeVar does not validate the decoded result. +const unsafe: Promise = choose('key'); +void text; +void integer; +void unsafe; +`, + 'utf8' + ); + const tscPath = join(process.cwd(), 'node_modules', 'typescript', 'lib', 'tsc.js'); + const compile = await processUtils.exec( + process.execPath, + [ + tscPath, + '--ignoreConfig', + '--noEmit', + '--pretty', + 'false', + '--target', + 'ES2022', + '--lib', + 'ES2022,DOM,DOM.Iterable', + '--module', + 'ESNext', + '--moduleResolution', + 'bundler', + '--skipLibCheck', + consumerPath, + ], + { cwd: process.cwd(), timeoutMs: 30_000 } + ); + expect(compile.code, `${compile.stdout}\n${compile.stderr}`).toBe(0); + expect(compile.stderr).toBe(''); + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }, 30_000); + it('generates safe generic wrappers and declaration files that typecheck', async () => { if (!(await supportsVariadicTypingFeatures())) { return; @@ -302,9 +458,9 @@ class Container(Generic[T]): const typescript = await fsUtils.readFile(join(outDir, 'generic_module.generated.ts')); const declaration = await fsUtils.readFile(join(outDir, 'generic_module.generated.d.ts')); - expect(typescript).toContain('export function identity(x: T): Promise;'); + expect(typescript).toContain('export function identity(x: T): Promise;'); expect(typescript).toContain( - 'export async function forward(container: Container): Promise>' + 'export async function forward(container: Container): Promise' ); expect(typescript).toContain( 'export async function acceptTransform

(' @@ -354,9 +510,11 @@ export declare function createReturnValidator(schema: ReturnSchema, const pair: Pair = ['a', 'b']; const transform: Transform<[number], string> = (...args) => String(args[0]); const container = {} as Container; -const accepted: Promise> = acceptTransform<[number], string>(transform); -const forwarded: Promise> = forward(container); -const resolved: Promise = identity(1); +const accepted: Promise = acceptTransform<[number], string>(transform); +const forwarded: Promise = forward(container); +const resolved: Promise = identity(1); +// @ts-expect-error The decoded generic result has no supported value contract. +const unsafe: Promise = identity(1); const passthroughResult: Promise = passthrough([1, 2], { flag: true }); void pair; @@ -364,6 +522,7 @@ void transform; void accepted; void forwarded; void resolved; +void unsafe; void passthroughResult; `, 'utf-8' diff --git a/test/ir-contract-validation.test.ts b/test/ir-contract-validation.test.ts new file mode 100644 index 00000000..2913b432 --- /dev/null +++ b/test/ir-contract-validation.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from 'vitest'; +import { TYWRAP_IR_VERSION, validateIrContract } from '../src/core/ir-contract.js'; + +const validContract = { + ir_version: TYWRAP_IR_VERSION, + module: 'fixture', + functions: [ + { + name: 'get_value', + qualname: 'fixture.get_value', + docstring: null, + parameters: [ + { name: 'key', kind: 'POSITIONAL_OR_KEYWORD', annotation: 'str | int', default: false }, + ], + returns: 'str | int', + is_async: false, + is_generator: false, + type_params: [], + method_kind: 'instance', + overloads: [ + { + parameters: [ + { name: 'key', kind: 'POSITIONAL_OR_KEYWORD', annotation: 'str', default: false }, + ], + returns: 'str', + }, + { + parameters: [ + { name: 'key', kind: 'POSITIONAL_OR_KEYWORD', annotation: 'int', default: false }, + ], + returns: 'int', + }, + ], + }, + ], + classes: [], + constants: [], + type_aliases: [], + metadata: {}, + warnings: [], +}; + +describe('validateIrContract', () => { + it('accepts the complete IR 0.4 callable shape, including overloads', () => { + const result = validateIrContract(validContract, 'fixture contract'); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.contract.functions[0]?.overloads).toHaveLength(2); + } + }); + + it('reports each malformed nested overload field at its JSON path', () => { + const invalid = structuredClone(validContract); + invalid.functions[0]!.overloads[1]!.parameters[0]!.kind = 'MALFORMED'; + invalid.functions[0]!.overloads[1]!.returns = 42 as unknown as string; + + const result = validateIrContract(invalid, 'fixture contract'); + + expect(result).toMatchObject({ ok: false }); + if (!result.ok) { + expect(result.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: 'contract-invalid', + path: '$.functions[0].overloads[1].parameters[0].kind', + }), + expect.objectContaining({ + code: 'contract-invalid', + path: '$.functions[0].overloads[1].returns', + }), + ]) + ); + } + }); + + it('keeps IR version mismatch separate from structural diagnostics', () => { + const invalid = { ...validContract, ir_version: '0.3.0' }; + const result = validateIrContract(invalid, 'fixture contract'); + + expect(result).toMatchObject({ ok: false }); + if (!result.ok) { + expect(result.diagnostics).toContainEqual( + expect.objectContaining({ code: 'ir-version-mismatch', path: '$.ir_version' }) + ); + } + }); + + it('reads stable offline contracts without extractor metadata', () => { + const offline = Object.fromEntries( + Object.entries(validContract).filter(([key]) => key !== 'metadata') + ); + const live = validateIrContract(offline, 'live IR'); + expect(live).toMatchObject({ ok: false }); + + const saved = validateIrContract(offline, 'saved contract', { + allowOmittedMetadata: true, + }); + expect(saved.ok).toBe(true); + if (saved.ok) { + expect(saved.contract.metadata).toEqual({}); + } + }); + + it('bounds malformed-contract diagnostics', () => { + const invalid = { + ...validContract, + functions: Array.from({ length: 120 }, () => ({ name: 2 })), + }; + const result = validateIrContract(invalid, 'bad contract'); + expect(result).toMatchObject({ ok: false }); + if (!result.ok) { + expect(result.diagnostics.length).toBeLessThanOrEqual(101); + expect(result.diagnostics.at(-1)?.message).toContain('more than 100 contract errors'); + } + }); + + it('rejects contracts that exceed the shared entry traversal limit', () => { + const oversized = { ...validContract, warnings: Array(100_001).fill('warning') }; + const result = validateIrContract(oversized, 'large contract'); + expect(result).toMatchObject({ ok: false }); + if (!result.ok) { + expect( + result.diagnostics.some(diagnostic => + diagnostic.message.includes('100000 entry validation limit') + ) + ).toBe(true); + } + }); +}); diff --git a/test/ir_contract.test.ts b/test/ir_contract.test.ts index cf57e5da..bcef9d35 100644 --- a/test/ir_contract.test.ts +++ b/test/ir_contract.test.ts @@ -1,9 +1,14 @@ import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; +import { pathToFileURL } from 'node:url'; import { describe, expect, it } from 'vitest'; +import ts from 'typescript'; import { generate } from '../src/tywrap.js'; +import { BridgeValidationError } from '../src/runtime/errors.js'; import { getDefaultPythonPath } from '../src/utils/python.js'; +import { processUtils } from '../src/utils/runtime.js'; +import { clearRuntimeBridge, setRuntimeBridge } from 'tywrap/runtime'; const pythonPath = getDefaultPythonPath(); @@ -17,6 +22,147 @@ function options(outputDir: string) { } describe('pinned IR contracts', () => { + it('keeps extracted positional-only overloads bound to their return types', async () => { + const tempDir = await mkdtemp(join(process.cwd(), 'test', '.tywrap-positional-')); + try { + const outputDir = join(tempDir, 'generated'); + const result = await generate({ + ...options(outputDir), + pythonModules: { positional_overloads: { typeHints: 'strict' as const } }, + pythonImportPath: ['test/fixtures/python'], + output: { dir: outputDir, format: 'esm', declaration: true, sourceMap: false }, + }); + expect(result.failures).toEqual([]); + + const contract = JSON.parse( + await readFile(join(outputDir, 'positional_overloads.contract.json'), 'utf8') + ) as { + functions: Array<{ + name: string; + parameters: Array<{ name: string; kind: string; default: boolean }>; + overloads: Array<{ + parameters: Array<{ name: string; kind: string; default: boolean }>; + returns: string; + }>; + }>; + }; + const choose = contract.functions.find(func => func.name === 'choose'); + expect(choose?.parameters.map(param => [param.name, param.kind, param.default])).toEqual([ + ['value', 'POSITIONAL_ONLY', false], + ['bias', 'POSITIONAL_OR_KEYWORD', true], + ['loud', 'KEYWORD_ONLY', true], + ]); + + const hasOverloadExtraction = await processUtils.exec(pythonPath, [ + '-c', + 'import typing; raise SystemExit(0 if hasattr(typing, "get_overloads") else 1)', + ]); + if (hasOverloadExtraction.code === 0) { + expect(choose?.overloads).toHaveLength(2); + expect( + choose?.overloads.map(overload => overload.parameters.map(param => param.kind)) + ).toEqual([ + ['POSITIONAL_ONLY', 'POSITIONAL_OR_KEYWORD', 'KEYWORD_ONLY'], + ['POSITIONAL_ONLY', 'POSITIONAL_OR_KEYWORD', 'KEYWORD_ONLY'], + ]); + expect(choose?.overloads.map(overload => overload.returns)).toEqual([ + expect.stringMatching(/str$/), + expect.stringMatching(/int$/), + ]); + + const consumerPath = join(outputDir, 'consumer.ts'); + await writeFile( + join(outputDir, 'contract.d.ts'), + await readFile(join(outputDir, 'positional_overloads.generated.d.ts'), 'utf8'), + 'utf8' + ); + await writeFile( + consumerPath, + [ + "import { choose } from './contract.js';", + "const text: Promise = choose('a');", + "const loudText: Promise = choose('a', undefined, { loud: true });", + 'const number: Promise = choose(4, 2, { loud: true });', + 'void text;', + 'void loudText;', + 'void number;', + '// @ts-expect-error value is positional-only', + "choose('a', undefined, { value: 'b' });", + '// @ts-expect-error the string overload returns a string', + "const wrong: Promise = choose('a');", + 'void wrong;', + ].join('\n'), + 'utf8' + ); + const program = ts.createProgram([consumerPath], { + noEmit: true, + strict: true, + skipLibCheck: true, + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + types: [], + }); + expect( + ts + .getPreEmitDiagnostics(program) + .map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')) + ).toEqual([]); + } else { + expect(choose?.overloads).toEqual([]); + } + + const source = await readFile(join(outputDir, 'positional_overloads.generated.ts'), 'utf8'); + const javascript = ts.transpileModule(source, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + const runtimePath = join(tempDir, 'positional_overloads.generated.mjs'); + await writeFile(runtimePath, javascript, 'utf8'); + const calls: Array<{ args: unknown[]; kwargs?: Record }> = []; + let wrongStringReturn = false; + setRuntimeBridge({ + async call( + _module: string, + _functionName: string, + args: unknown[], + kwargs?: Record, + validate?: (result: T) => void + ): Promise { + calls.push({ args: [...args], kwargs }); + const value = + typeof args[0] === 'string' + ? wrongStringReturn + ? 7 + : args[0] + : Number(args[0]) + Number(args[1] ?? 0); + validate?.(value as T); + return value as T; + }, + async dispose(): Promise {}, + }); + const generated = (await import(pathToFileURL(runtimePath).href)) as { + choose: (...args: unknown[]) => Promise; + }; + await expect(generated.choose('a')).resolves.toBe('a'); + await expect(generated.choose('a', undefined, { loud: true })).resolves.toBe('a'); + await expect(generated.choose(4, 2, { loud: true })).resolves.toBe(6); + await expect(generated.choose('a', undefined, { value: 'b' })).rejects.toThrow( + /positional-only argument "value"/ + ); + expect(calls).toHaveLength(3); + expect(calls[0]?.args).toEqual(['a']); + expect(calls[1]).toEqual({ args: ['a'], kwargs: { loud: true } }); + expect(calls[2]).toEqual({ args: [4, 2], kwargs: { loud: true } }); + if (hasOverloadExtraction.code === 0) { + wrongStringReturn = true; + await expect(generated.choose('a')).rejects.toThrow(BridgeValidationError); + } + } finally { + clearRuntimeBridge(); + await rm(tempDir, { recursive: true, force: true }); + } + }); + it('writes stable sorted contracts and detects contract drift in check mode', async () => { const tempDir = await mkdtemp(join(tmpdir(), 'tywrap-ir-contract-')); try { @@ -96,6 +242,93 @@ describe('pinned IR contracts', () => { } }); + it('keeps a supported NumPy float16 contract strict in offline and check modes', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'tywrap-ir-float16-')); + try { + const contractPath = join(tempDir, 'scientific.contract.json'); + await writeFile( + contractPath, + JSON.stringify({ + ir_version: '0.4.0', + module: 'scientific_fixture', + functions: [ + { + name: 'value', + qualname: 'scientific_fixture.value', + docstring: null, + parameters: [], + returns: 'numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[numpy.float16]]', + is_async: false, + is_generator: false, + type_params: [], + method_kind: 'instance', + overloads: [], + }, + ], + classes: [], + constants: [], + type_aliases: [], + metadata: {}, + warnings: [ + 'Return annotation for scientific_fixture.value resolves outside analyzed module: numpy.ndarray.', + ], + }), + 'utf8' + ); + const configured = { + ...options(join(tempDir, 'generated')), + pythonModules: { scientific_fixture: { typeHints: 'strict' as const } }, + contractInput: contractPath, + }; + const first = await generate(configured); + expect(first.failures).toEqual([]); + expect(first.warnings).toEqual([]); + const emitted = await readFile( + join(tempDir, 'generated', 'scientific_fixture.generated.ts'), + 'utf8' + ); + expect(emitted).toContain('value(): Promise<__tywrapFloat16Value>'); + expect(emitted).toContain('"marker":"ndarray","dtype":"float16"'); + const check = await generate(configured, { check: true }); + expect(check.failures).toEqual([]); + expect(check.warnings).toEqual([]); + expect(check.outOfDate).toEqual([]); + + const foreign = JSON.parse(await readFile(contractPath, 'utf8')) as { + functions: Array<{ returns: string }>; + warnings: string[]; + }; + foreign.functions[0]!.returns = + 'numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[external.float16]]'; + await writeFile(contractPath, JSON.stringify(foreign), 'utf8'); + const rejected = await generate(configured); + expect( + rejected.warnings.some(warning => + warning.includes('no value conversion is defined for numpy.ndarray') + ) + ).toBe(true); + expect( + rejected.warnings.some(warning => + warning.includes('resolves outside analyzed module: numpy.ndarray') + ) + ).toBe(true); + + foreign.functions[0]!.returns = + 'numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[numpy.float16]]'; + foreign.warnings[0] = + 'Return annotation for scientific_fixture.value resolves outside analyzed module: numpy.Opaque.'; + await writeFile(contractPath, JSON.stringify(foreign), 'utf8'); + const unrelated = await generate(configured); + expect( + unrelated.warnings.some(warning => + warning.includes('resolves outside analyzed module: numpy.Opaque') + ) + ).toBe(true); + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }); + // Windows cannot run the fake-interpreter shim: extensionless sh scripts // fail with ENOENT and .cmd files fail with EINVAL (Node's batch-file spawn // mitigation; the production spawn rightly never sets shell:true). The diff --git a/test/ir_extraction_advanced.test.ts b/test/ir_extraction_advanced.test.ts index a3ddb785..0e2804f5 100644 --- a/test/ir_extraction_advanced.test.ts +++ b/test/ir_extraction_advanced.test.ts @@ -209,6 +209,39 @@ describe('IR Extraction - Complex Fixture Files', () => { }); describe('IR Extraction - Generic Metadata', () => { + it('keeps type parameters declared only in overload signatures', async () => { + const version = await processUtils.exec(PYTHON_EXECUTABLE, [ + '-c', + 'import typing; raise SystemExit(0 if hasattr(typing, "get_overloads") else 1)', + ]); + if (version.code !== 0) { + return; + } + + createTempModule( + 'overload_only_generic', + `from typing import TypeVar, overload + +T = TypeVar("T") + +@overload +def choose(value: T) -> T: ... + +@overload +def choose(value: None) -> None: ... + +def choose(value: object) -> object: + return value +` + ); + + const ir = await extractIR('overload_only_generic'); + const choose = ir.functions.find((item: { name: string }) => item.name === 'choose'); + expect(choose.type_params.map((param: { name: string }) => param.name)).toEqual(['T']); + expect(choose.overloads).toHaveLength(2); + expect(choose.overloads[0].parameters[0].annotation).toMatch(/T$/); + }); + it('extracts ordered type parameters for functions, classes, and type aliases', async () => { if (!(await supportsVariadicTypingFeatures())) { return; diff --git a/test/ir_version_drift.test.ts b/test/ir_version_drift.test.ts index a929532b..00f96f21 100644 --- a/test/ir_version_drift.test.ts +++ b/test/ir_version_drift.test.ts @@ -9,7 +9,7 @@ import { describe, expect, it } from 'vitest'; * so this test runs without a Python interpreter and without pulling tywrap.ts' * dependency graph into the test process. The single sources are: * - Python: tywrap_ir/tywrap_ir/__init__.py (IR_VERSION = "...") - * - TypeScript: src/tywrap.ts (const TYWRAP_IR_VERSION = '...') + * - TypeScript: src/core/ir-contract.ts (const TYWRAP_IR_VERSION = '...') */ const repoRoot = process.cwd(); @@ -32,7 +32,7 @@ describe('IR_VERSION drift', () => { 'IR_VERSION' ); const tsVersion = readVersion( - join('src', 'tywrap.ts'), + join('src', 'core', 'ir-contract.ts'), /\bTYWRAP_IR_VERSION\s*=\s*["']([^"']+)["']/, 'TYWRAP_IR_VERSION' ); diff --git a/test/isolated_consumer.conformance.ts b/test/isolated_consumer.conformance.ts new file mode 100644 index 00000000..7d1e1e6a --- /dev/null +++ b/test/isolated_consumer.conformance.ts @@ -0,0 +1,614 @@ +import { execFile } from 'node:child_process'; +import { + copyFileSync, + existsSync, + mkdtempSync, + mkdirSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { promisify } from 'node:util'; + +import { afterAll, describe, expect, it } from 'vitest'; + +const execFileAsync = promisify(execFile); +const repoRoot = resolve(process.cwd()); +const python = process.env.PYTHON ?? (process.platform === 'win32' ? 'python' : 'python3'); +const tempRoot = mkdtempSync(join(tmpdir(), 'tywrap-isolated-consumer-')); +const npmRegistry = 'https://registry.npmjs.org/'; +const pypiRegistry = 'https://pypi.org/simple'; + +type ConsumerMode = + | { kind: 'candidate' } + | { kind: 'published'; npmVersion: string; pypiVersion: string }; + +const npmExactVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/; +const pypiExactVersion = /^\d+\.\d+\.\d+(?:(?:a|b|rc)\d+)?(?:\.post\d+)?(?:\.dev\d+)?$/; +const pypiHyphenatedPrerelease = + /^(\d+\.\d+\.\d+)-(alpha|beta|rc)[.-]?(0|[1-9]\d*)((?:\.post\d+)?(?:\.dev\d+)?)$/; + +function canonicalPyPiVersion(version: string): string { + return version.replace( + pypiHyphenatedPrerelease, + (_match, release: string, label: string, number: string, suffix: string) => { + const shortLabel = label === 'alpha' ? 'a' : label === 'beta' ? 'b' : 'rc'; + return `${release}${shortLabel}${number}${suffix}`; + } + ); +} + +function isExactPublishedVersion( + version: string | undefined, + registry: 'npm' | 'pypi' +): version is string { + if (!version) return false; + return registry === 'npm' + ? npmExactVersion.test(version) + : pypiExactVersion.test(canonicalPyPiVersion(version)); +} + +function consumerMode(env: NodeJS.ProcessEnv = process.env): ConsumerMode { + const mode = env.TYWRAP_CONSUMER_MODE ?? 'candidate'; + const npmVersion = env.TYWRAP_PUBLISHED_NPM_VERSION; + const pypiVersion = env.TYWRAP_PUBLISHED_PYPI_VERSION; + if (mode === 'candidate') { + if (npmVersion !== undefined || pypiVersion !== undefined) { + throw new Error('Published versions require TYWRAP_CONSUMER_MODE=published'); + } + return { kind: 'candidate' }; + } + if (mode !== 'published') { + throw new Error(`Unknown consumer mode: ${mode}`); + } + if (!isExactPublishedVersion(npmVersion, 'npm')) { + throw new Error('TYWRAP_PUBLISHED_NPM_VERSION must be an exact npm version'); + } + if (!isExactPublishedVersion(pypiVersion, 'pypi')) { + throw new Error('TYWRAP_PUBLISHED_PYPI_VERSION must be an exact PyPI version'); + } + return { kind: 'published', npmVersion, pypiVersion }; +} + +interface CommandOptions { + cwd: string; + env?: NodeJS.ProcessEnv; + timeout?: number; +} + +function isInside(child: string, parent: string): boolean { + const relation = relative(resolve(parent), resolve(child)); + return ( + relation === '' || + (!isAbsolute(relation) && relation !== '..' && !relation.startsWith(`..${sep}`)) + ); +} + +async function run(command: string, args: string[], options: CommandOptions): Promise { + try { + const { stdout } = await execFileAsync(command, args, { + cwd: options.cwd, + env: options.env, + timeout: options.timeout ?? 60_000, + maxBuffer: 10 * 1024 * 1024, + }); + return stdout; + } catch (error: unknown) { + const result = error as { stderr?: string; stdout?: string; message?: string }; + throw new Error( + `${command} ${args.join(' ')} failed: ${result.stderr ?? result.stdout ?? result.message ?? 'unknown error'}` + ); + } +} + +function venvPython(venv: string): string { + return process.platform === 'win32' + ? join(venv, 'Scripts', 'python.exe') + : join(venv, 'bin', 'python'); +} + +describe('isolated npm consumer', () => { + afterAll(() => { + rmSync(tempRoot, { recursive: true, force: true }); + }); + + it('uses candidate mode unless both exact published versions are selected', () => { + expect(consumerMode({})).toEqual({ kind: 'candidate' }); + expect( + consumerMode({ + TYWRAP_CONSUMER_MODE: 'published', + TYWRAP_PUBLISHED_NPM_VERSION: '1.2.3', + TYWRAP_PUBLISHED_PYPI_VERSION: '4.5.6', + }) + ).toEqual({ kind: 'published', npmVersion: '1.2.3', pypiVersion: '4.5.6' }); + }); + + it('accepts the stable release pair and canonical PyPI prereleases', () => { + expect( + consumerMode({ + TYWRAP_CONSUMER_MODE: 'published', + TYWRAP_PUBLISHED_NPM_VERSION: '0.11.0', + TYWRAP_PUBLISHED_PYPI_VERSION: '0.3.1', + }) + ).toEqual({ kind: 'published', npmVersion: '0.11.0', pypiVersion: '0.3.1' }); + expect(isExactPublishedVersion('0.3.1rc1.post2.dev3', 'pypi')).toBe(true); + }); + + it.each([ + ['0.11.0-rc-1', '0.3.1-rc-1'], + ['0.11.0-rc.1', '0.3.1-rc.1'], + ['0.11.0-alpha.2', '0.3.1-alpha.2'], + ])('accepts exact project prereleases %s and %s', (npmVersion, pypiVersion) => { + expect( + consumerMode({ + TYWRAP_CONSUMER_MODE: 'published', + TYWRAP_PUBLISHED_NPM_VERSION: npmVersion, + TYWRAP_PUBLISHED_PYPI_VERSION: pypiVersion, + }) + ).toEqual({ kind: 'published', npmVersion, pypiVersion }); + }); + + it.each([ + ['0.3.1-rc-1', '0.3.1rc1'], + ['0.3.1-rc.1', '0.3.1rc1'], + ['0.3.1-alpha.2', '0.3.1a2'], + ['0.3.1-beta-3', '0.3.1b3'], + ['0.3.1rc1.post2.dev3', '0.3.1rc1.post2.dev3'], + ])('compares PyPI metadata using canonical version %s', (version, canonical) => { + expect(canonicalPyPiVersion(version)).toBe(canonical); + }); + + it.each([ + { TYWRAP_CONSUMER_MODE: 'published', TYWRAP_PUBLISHED_PYPI_VERSION: '4.5.6' }, + { TYWRAP_CONSUMER_MODE: 'published', TYWRAP_PUBLISHED_NPM_VERSION: '1.2.3' }, + { + TYWRAP_CONSUMER_MODE: 'published', + TYWRAP_PUBLISHED_NPM_VERSION: 'latest', + TYWRAP_PUBLISHED_PYPI_VERSION: '4.5.6', + }, + { + TYWRAP_CONSUMER_MODE: 'published', + TYWRAP_PUBLISHED_NPM_VERSION: '1.2.3', + TYWRAP_PUBLISHED_PYPI_VERSION: '>=4.5', + }, + { TYWRAP_PUBLISHED_NPM_VERSION: '1.2.3' }, + { + TYWRAP_CONSUMER_MODE: 'published', + TYWRAP_PUBLISHED_NPM_VERSION: '0.11.0-rc-1', + TYWRAP_PUBLISHED_PYPI_VERSION: '0.3.1-foo.1', + }, + { + TYWRAP_CONSUMER_MODE: 'published', + TYWRAP_PUBLISHED_NPM_VERSION: '0.11.0-rc-1', + TYWRAP_PUBLISHED_PYPI_VERSION: '0.3.1-rc-01', + }, + { + TYWRAP_CONSUMER_MODE: 'published', + TYWRAP_PUBLISHED_NPM_VERSION: '0.11.0+build.1', + TYWRAP_PUBLISHED_PYPI_VERSION: '0.3.1', + }, + { + TYWRAP_CONSUMER_MODE: 'published', + TYWRAP_PUBLISHED_NPM_VERSION: '0.11.0', + TYWRAP_PUBLISHED_PYPI_VERSION: '1!0.3.1', + }, + ])('rejects an incomplete or floating published version pair', env => { + expect(() => consumerMode(env)).toThrow(); + }); + + it('installs, generates, compiles, and executes without repository Python imports', async () => { + const mode = consumerMode(); + const artifacts = join(tempRoot, 'artifacts'); + const consumer = join(tempRoot, 'consumer'); + const fixtures = join(consumer, 'fixtures'); + const venv = join(tempRoot, 'venv'); + const wheelDir = join(artifacts, 'wheels'); + mkdirSync(fixtures, { recursive: true }); + + let packageSpec: string; + if (mode.kind === 'candidate') { + mkdirSync(artifacts, { recursive: true }); + const packOutput = await run('npm', ['pack', '--json', '--pack-destination', artifacts], { + cwd: repoRoot, + timeout: 180_000, + }); + const pack = JSON.parse(packOutput) as Array<{ filename?: string }>; + const filename = pack[0]?.filename; + if (!filename) { + throw new Error('npm pack did not return a package filename'); + } + packageSpec = join(artifacts, filename); + expect(existsSync(packageSpec)).toBe(true); + } else { + packageSpec = `tywrap@${mode.npmVersion}`; + } + + await run(python, ['-m', 'venv', venv], { cwd: tempRoot }); + const isolatedPython = venvPython(venv); + expect(existsSync(isolatedPython)).toBe(true); + await run( + isolatedPython, + [ + '-c', + 'import sys\nif sys.version_info < (3, 11): raise SystemExit("Python 3.11 is required for overload extraction")', + ], + { cwd: consumer } + ); + + if (mode.kind === 'candidate') { + mkdirSync(wheelDir, { recursive: true }); + await run( + isolatedPython, + [ + '-m', + 'pip', + 'install', + '--disable-pip-version-check', + '--upgrade', + 'setuptools>=68', + 'wheel', + ], + { cwd: tempRoot, timeout: 120_000 } + ); + await run( + isolatedPython, + ['-m', 'pip', 'install', '--disable-pip-version-check', 'numpy==2.3.5', 'pyarrow==24.0.0'], + { cwd: tempRoot, timeout: 180_000 } + ); + await run( + isolatedPython, + [ + '-m', + 'pip', + 'wheel', + '--no-deps', + '--no-build-isolation', + '--wheel-dir', + wheelDir, + join(repoRoot, 'tywrap_ir'), + ], + { cwd: tempRoot, timeout: 120_000 } + ); + const wheels = ( + await run(isolatedPython, ['-c', 'import glob; print(*glob.glob("*.whl"))'], { + cwd: wheelDir, + }) + ) + .trim() + .split(/\s+/) + .filter(Boolean); + expect(wheels).toHaveLength(1); + await run( + isolatedPython, + [ + '-m', + 'pip', + 'install', + '--no-index', + '--find-links', + wheelDir, + join(wheelDir, wheels[0] as string), + ], + { cwd: tempRoot, timeout: 120_000 } + ); + } else { + const reportPath = join(tempRoot, 'pypi-install-report.json'); + await run( + isolatedPython, + [ + '-m', + 'pip', + '--isolated', + 'install', + '--disable-pip-version-check', + '--no-cache-dir', + '--only-binary=:all:', + '--index-url', + pypiRegistry, + '--report', + reportPath, + `tywrap-ir==${mode.pypiVersion}`, + 'numpy==2.3.5', + 'pyarrow==24.0.0', + ], + { cwd: tempRoot, timeout: 180_000 } + ); + const report = JSON.parse(readFileSync(reportPath, 'utf8')) as { + install?: Array<{ + metadata?: { name?: string; version?: string }; + download_info?: { url?: string }; + }>; + }; + const irInstall = report.install?.find( + item => item.metadata?.name?.toLowerCase().replace(/[-_.]+/g, '-') === 'tywrap-ir' + ); + expect(irInstall?.metadata?.version).toBe(canonicalPyPiVersion(mode.pypiVersion)); + expect(new URL(irInstall?.download_info?.url ?? '').hostname).toBe('files.pythonhosted.org'); + } + + writeFileSync( + join(fixtures, 'consumer_fixture.py'), + [ + 'import numpy as np', + 'from numpy.typing import NDArray', + '', + 'def add(left: int, right: int) -> int:', + ' return left + right', + '', + 'def safe_max() -> int:', + ' return 2**53 - 1', + '', + 'def safe_min() -> int:', + ' return -(2**53 - 1)', + '', + 'def unsafe_positive() -> int:', + ' return 2**53', + '', + 'def unsafe_negative() -> int:', + ' return -(2**53)', + '', + 'def float16_values() -> NDArray[np.float16]:', + ' return np.array([1.5, -2.25, -0.0], dtype=np.float16)', + '', + 'def wrong_return() -> int:', + ' return "not an integer"', + '', + ].join('\n'), + 'utf8' + ); + copyFileSync( + join(repoRoot, 'test', 'fixtures', 'architecture_callable_fixture.py'), + join(fixtures, 'architecture_callable_fixture.py') + ); + writeFileSync( + join(consumer, 'package.json'), + `${JSON.stringify({ name: 'tywrap-consumer-check', private: true, type: 'module' }, null, 2)}\n`, + 'utf8' + ); + const npmArgs = ['install', '--ignore-scripts', '--no-audit', '--no-fund']; + if (mode.kind === 'published') { + npmArgs.push( + '--registry', + npmRegistry, + '--cache', + join(tempRoot, 'npm-registry-cache'), + '--prefer-online' + ); + } + npmArgs.push(packageSpec, 'apache-arrow@21.1.0'); + await run('npm', npmArgs, { cwd: consumer, timeout: 180_000 }); + + const installedPackage = realpathSync(join(consumer, 'node_modules', 'tywrap')); + expect(isInside(installedPackage, consumer)).toBe(true); + expect(isInside(installedPackage, repoRoot)).toBe(false); + if (mode.kind === 'published') { + const packageJson = JSON.parse( + readFileSync(join(installedPackage, 'package.json'), 'utf8') + ) as { + version?: string; + }; + expect(packageJson.version).toBe(mode.npmVersion); + const lock = JSON.parse(readFileSync(join(consumer, 'package-lock.json'), 'utf8')) as { + packages?: Record; + }; + expect(lock.packages?.['node_modules/tywrap']?.resolved).toBe( + `${npmRegistry}tywrap/-/tywrap-${mode.npmVersion}.tgz` + ); + } + expect(existsSync(join(installedPackage, 'dist', 'cli.js'))).toBe(true); + expect(existsSync(join(installedPackage, 'runtime', 'python_bridge.py'))).toBe(true); + expect(isInside(realpathSync(join(consumer, 'node_modules', 'apache-arrow')), consumer)).toBe( + true + ); + + const isolatedPythonEnv: NodeJS.ProcessEnv = { + ...process.env, + PYTHONNOUSERSITE: '1', + PYTHONPATH: fixtures, + }; + const importedIrPath = ( + await run( + isolatedPython, + ['-c', 'import pathlib, tywrap_ir; print(pathlib.Path(tywrap_ir.__file__).resolve())'], + { cwd: consumer, env: isolatedPythonEnv } + ) + ).trim(); + expect(isInside(importedIrPath, venv)).toBe(true); + expect(isInside(importedIrPath, repoRoot)).toBe(false); + if (mode.kind === 'published') { + const installedIr = JSON.parse( + await run( + isolatedPython, + [ + '-c', + 'import importlib.metadata as m, json; d=m.distribution("tywrap-ir"); print(json.dumps({"version": d.version, "direct_url": d.read_text("direct_url.json")}))', + ], + { cwd: consumer, env: isolatedPythonEnv } + ) + ) as { version?: string; direct_url?: string | null }; + expect(installedIr.version).toBe(canonicalPyPiVersion(mode.pypiVersion)); + expect(installedIr.direct_url).toBeNull(); + } + + const generated = join(consumer, 'generated'); + expect(existsSync(generated)).toBe(false); + writeFileSync( + join(consumer, 'tywrap.config.json'), + `${JSON.stringify( + { + pythonModules: { + consumer_fixture: { typeHints: 'strict' }, + architecture_callable_fixture: { typeHints: 'strict' }, + }, + pythonImportPath: [fixtures], + output: { dir: generated, format: 'esm', declaration: false, sourceMap: false }, + runtime: { node: { pythonPath: isolatedPython } }, + performance: { caching: false, batching: false, compression: 'none' }, + }, + null, + 2 + )}\n`, + 'utf8' + ); + await run( + process.execPath, + [ + join(installedPackage, 'dist', 'cli.js'), + 'generate', + '--config', + 'tywrap.config.json', + '--fail-on-warn', + ], + { cwd: consumer, env: isolatedPythonEnv, timeout: 60_000 } + ); + + const generatedSource = join(generated, 'consumer_fixture.generated.ts'); + expect(existsSync(generatedSource)).toBe(true); + expect(readFileSync(generatedSource, 'utf8')).not.toContain(repoRoot); + const architectureSource = join(generated, 'architecture_callable_fixture.generated.ts'); + expect(existsSync(architectureSource)).toBe(true); + expect(readFileSync(architectureSource, 'utf8')).not.toContain(repoRoot); + copyFileSync( + join(repoRoot, 'test', 'fixtures', 'architecture-overload.typecheck.ts.txt'), + join(consumer, 'architecture-overload.typecheck.ts') + ); + writeFileSync( + join(consumer, 'tsconfig.json'), + `${JSON.stringify( + { + compilerOptions: { + target: 'ES2022', + module: 'NodeNext', + moduleResolution: 'NodeNext', + rootDir: '.', + outDir: 'built', + strict: true, + skipLibCheck: true, + }, + include: ['generated/**/*.ts', 'architecture-overload.typecheck.ts'], + }, + null, + 2 + )}\n`, + 'utf8' + ); + await run( + process.execPath, + [join(consumer, 'node_modules', 'typescript', 'lib', 'tsc.js'), '--project', 'tsconfig.json'], + { + cwd: consumer, + } + ); + + const runner = join(consumer, 'run-generated-wrapper.mjs'); + writeFileSync( + runner, + `import { BridgeValidationError } from 'tywrap'; +import { NodeBridge } from 'tywrap/node'; +import { clearRuntimeBridge, setRuntimeBridge } from 'tywrap/runtime'; +import * as fixture from './built/generated/consumer_fixture.generated.js'; +import * as architecture from './built/generated/architecture_callable_fixture.generated.js'; + +const [pythonPath, fixtures] = process.argv.slice(2); +const bridge = new NodeBridge({ + pythonPath, + cwd: process.cwd(), + env: { + PYTHONNOUSERSITE: '1', + PYTHONPATH: fixtures, + TYWRAP_ALLOWED_MODULES: 'consumer_fixture,architecture_callable_fixture', + }, +}); + +try { + setRuntimeBridge({ call: bridge.call.bind(bridge), dispose: bridge.dispose.bind(bridge) }); + const add = await fixture.add(2, 3); + const safeMax = await fixture.safeMax(); + const safeMin = await fixture.safeMin(); + const float16Values = await fixture.float16Values(); + if (!Array.isArray(float16Values) || float16Values.length !== 3) { + throw new Error('float16_values did not decode to a three-element array'); + } + const negativeZero = Object.is(float16Values[2], -0); + for (const call of [fixture.unsafePositive, fixture.unsafeNegative]) { + let unsafeError; + try { + await call(); + } catch (error) { + unsafeError = error; + } + if ( + unsafeError?.name !== 'BridgeExecutionError' || + !unsafeError.message.includes('result') || + !unsafeError.message.includes('safe integer range') || + !unsafeError.message.includes('explicit string') + ) { + throw new Error('unsafe integer did not fail with a located conversion error'); + } + } + let validationError; + try { + await fixture.wrongReturn(); + } catch (error) { + validationError = error; + } + if (!(validationError instanceof BridgeValidationError)) { + throw new Error('wrong_return did not throw BridgeValidationError'); + } + const textRecord = await architecture.selectRecord('label'); + const integerRecord = await architecture.selectRecord(42); + for (const key of ['label', 42]) { + let wrongOverloadError; + try { + await architecture.selectRecordWrong(key); + } catch (error) { + wrongOverloadError = error; + } + if ( + !(wrongOverloadError instanceof BridgeValidationError) || + wrongOverloadError.callSite !== 'architecture_callable_fixture.select_record_wrong' + ) { + throw new Error('selected overload accepted a wrong nested return'); + } + } + let wrongIntegerError; + try { + await architecture.wrongIntegerReturn(); + } catch (error) { + wrongIntegerError = error; + } + if ( + !(wrongIntegerError instanceof BridgeValidationError) || + wrongIntegerError.callSite !== 'architecture_callable_fixture.wrong_integer_return' + ) { + throw new Error('wrong_integer_return did not throw BridgeValidationError'); + } + process.stdout.write(JSON.stringify({ + add, safeMax, safeMin, float16Values, negativeZero, textRecord, integerRecord, + })); +} finally { + clearRuntimeBridge(); + await bridge.dispose(); +} +`, + 'utf8' + ); + const execution = await run(process.execPath, [runner, isolatedPython, fixtures], { + cwd: consumer, + env: isolatedPythonEnv, + timeout: 60_000, + }); + expect(JSON.parse(execution)).toEqual({ + add: 5, + safeMax: Number.MAX_SAFE_INTEGER, + safeMin: Number.MIN_SAFE_INTEGER, + float16Values: [1.5, -2.25, 0], + negativeZero: true, + textRecord: { outer: { value: 'label' } }, + integerRecord: { outer: { value: 42 } }, + }); + }, 240_000); +}); diff --git a/test/menagerie/__snapshots__/gen.test.ts.snap b/test/menagerie/__snapshots__/gen.test.ts.snap index 36295109..6b2979da 100644 --- a/test/menagerie/__snapshots__/gen.test.ts.snap +++ b/test/menagerie/__snapshots__/gen.test.ts.snap @@ -10,7 +10,7 @@ import { createReturnValidator, getRuntimeBridge, type ReturnSchema } from 'tywr const __tywrapReturnDefinitions: Record = {"Movie":{"kind":"record","fields":{"title":{"schema":{"kind":"primitive","type":"string"},"optional":false},"year":{"schema":{"kind":"primitive","type":"number"},"optional":false}}},"RatedMovie":{"kind":"record","fields":{"title":{"schema":{"kind":"primitive","type":"string"},"optional":false},"year":{"schema":{"kind":"primitive","type":"number"},"optional":false},"rating":{"schema":{"kind":"primitive","type":"number"},"optional":true}}}}; -const __validateannotated_echoResult = createReturnValidator({"kind":"primitive","type":"number"}, "fixtures.typing_torture.annotated_echo", __tywrapReturnDefinitions); +const __validateannotated_echoResult = createReturnValidator({"kind":"primitive","type":"number","constraint":"safe-integer"}, "fixtures.typing_torture.annotated_echo", __tywrapReturnDefinitions); export async function annotatedEcho(value: number): Promise { const __args: unknown[] = [value]; @@ -47,16 +47,16 @@ export async function generatorValues(): Promise { const __validategeneric_identityResult = createReturnValidator({"kind":"any"}, "fixtures.typing_torture.generic_identity", __tywrapReturnDefinitions); -export async function genericIdentity(value: T): Promise { +export async function genericIdentity(value: T): Promise { const __args: unknown[] = [value]; - return getRuntimeBridge().call('fixtures.typing_torture', 'generic_identity', __args, undefined, __validategeneric_identityResult); + return getRuntimeBridge().call('fixtures.typing_torture', 'generic_identity', __args, undefined, __validategeneric_identityResult); } -const __validateint_key_dictResult = createReturnValidator({"kind":"record","values":{"kind":"primitive","type":"string"}}, "fixtures.typing_torture.int_key_dict", __tywrapReturnDefinitions); +const __validateint_key_dictResult = createReturnValidator({"kind":"any"}, "fixtures.typing_torture.int_key_dict", __tywrapReturnDefinitions); -export async function intKeyDict(value: { [key: number]: string; }): Promise<{ [key: number]: string; }> { +export async function intKeyDict(value: unknown): Promise { const __args: unknown[] = [value]; - return getRuntimeBridge().call<{ [key: number]: string; }>('fixtures.typing_torture', 'int_key_dict', __args, undefined, __validateint_key_dictResult); + return getRuntimeBridge().call('fixtures.typing_torture', 'int_key_dict', __args, undefined, __validateint_key_dictResult); } const __validateiterator_valuesResult = createReturnValidator({"kind":"any"}, "fixtures.typing_torture.iterator_values", __tywrapReturnDefinitions); @@ -68,42 +68,39 @@ export async function iteratorValues(): Promise { const __validateliteral_echoResult = createReturnValidator({"kind":"union","options":[{"kind":"literal","value":"red"},{"kind":"literal","value":"blue"},{"kind":"literal","value":7}]}, "fixtures.typing_torture.literal_echo", __tywrapReturnDefinitions); -export async function literalEcho(value: "red" | "blue" | 7): Promise<"red" | "blue" | 7> { +export async function literalEcho(value: "red" | "blue" | 7): Promise { const __args: unknown[] = [value]; - return getRuntimeBridge().call<"red" | "blue" | 7>('fixtures.typing_torture', 'literal_echo', __args, undefined, __validateliteral_echoResult); + return getRuntimeBridge().call('fixtures.typing_torture', 'literal_echo', __args, undefined, __validateliteral_echoResult); } -const __validatenested_containersResult = createReturnValidator({"kind":"array","element":{"kind":"record","values":{"kind":"array","element":{"kind":"tuple","elements":[{"kind":"primitive","type":"number"},{"kind":"primitive","type":"string"}]}}}}, "fixtures.typing_torture.nested_containers", __tywrapReturnDefinitions); +const __validatenested_containersResult = createReturnValidator({"kind":"array","element":{"kind":"record","fields":{},"values":{"kind":"array","element":{"kind":"tuple","elements":[{"kind":"primitive","type":"number","constraint":"safe-integer"},{"kind":"primitive","type":"string"}]}}}}, "fixtures.typing_torture.nested_containers", __tywrapReturnDefinitions); export async function nestedContainers(value: Record[]): Promise[]> { const __args: unknown[] = [value]; return getRuntimeBridge().call[]>('fixtures.typing_torture', 'nested_containers', __args, undefined, __validatenested_containersResult); } -const __validatenone_returnResult = createReturnValidator({"kind":"any"}, "fixtures.typing_torture.none_return", __tywrapReturnDefinitions); +const __validatenone_returnResult = createReturnValidator({"kind":"primitive","type":"null"}, "fixtures.typing_torture.none_return", __tywrapReturnDefinitions); export async function noneReturn(): Promise { const __args: unknown[] = []; return getRuntimeBridge().call('fixtures.typing_torture', 'none_return', __args, undefined, __validatenone_returnResult); } -const __validateoptional_unionResult = createReturnValidator({"kind":"union","options":[{"kind":"primitive","type":"string"},{"kind":"primitive","type":"number"},{"kind":"primitive","type":"null"}]}, "fixtures.typing_torture.optional_union", __tywrapReturnDefinitions); +const __validateoptional_unionResult = createReturnValidator({"kind":"union","options":[{"kind":"primitive","type":"string"},{"kind":"primitive","type":"number","constraint":"safe-integer"},{"kind":"primitive","type":"null"}]}, "fixtures.typing_torture.optional_union", __tywrapReturnDefinitions); export async function optionalUnion(value: string | number | null): Promise { const __args: unknown[] = [value]; return getRuntimeBridge().call('fixtures.typing_torture', 'optional_union', __args, undefined, __validateoptional_unionResult); } -const __validateoverloadedResult = createReturnValidator({"kind":"union","options":[{"kind":"primitive","type":"number"},{"kind":"primitive","type":"string"}]}, "fixtures.typing_torture.overloaded", __tywrapReturnDefinitions); +const __validateoverloadedResult = createReturnValidator({"kind":"union","options":[{"kind":"primitive","type":"number","constraint":"safe-integer"},{"kind":"primitive","type":"string"}]}, "fixtures.typing_torture.overloaded", __tywrapReturnDefinitions); -export async function overloaded(value: number | string): Promise { - const __args: unknown[] = [value]; - return getRuntimeBridge().call('fixtures.typing_torture', 'overloaded', __args, undefined, __validateoverloadedResult); -} +/* overload implementation checked separately */ const __validateparamspec_applyResult = createReturnValidator({"kind":"any"}, "fixtures.typing_torture.paramspec_apply", __tywrapReturnDefinitions); -export async function paramspecApply

(callback: (...args: P) => T, args?: unknown[], kwargs?: Record): Promise { +export async function paramspecApply

(callback: (...args: P) => T, args?: unknown[], kwargs?: Record): Promise { let __kwargs = kwargs; const __args: unknown[] = [callback]; let __varargs: unknown[] = []; @@ -117,52 +114,52 @@ export async function paramspecApply

(callback: (...args: } } __args.push(...__varargs); - return getRuntimeBridge().call('fixtures.typing_torture', 'paramspec_apply', __args, __kwargs, __validateparamspec_applyResult); + return getRuntimeBridge().call('fixtures.typing_torture', 'paramspec_apply', __args, __kwargs, __validateparamspec_applyResult); } const __validateprotocol_identityResult = createReturnValidator({"kind":"any"}, "fixtures.typing_torture.protocol_identity", __tywrapReturnDefinitions); -export async function protocolIdentity(value: SupportsClose): Promise { +export async function protocolIdentity(value: SupportsClose): Promise { const __args: unknown[] = [value]; - return getRuntimeBridge().call('fixtures.typing_torture', 'protocol_identity', __args, undefined, __validateprotocol_identityResult); + return getRuntimeBridge().call('fixtures.typing_torture', 'protocol_identity', __args, undefined, __validateprotocol_identityResult); } -const __validaterated_movieResult = createReturnValidator({"kind":"ref","name":"RatedMovie"}, "fixtures.typing_torture.rated_movie", __tywrapReturnDefinitions); +const __validaterated_movieResult = createReturnValidator({"kind":"record","fields":{"title":{"schema":{"kind":"primitive","type":"string"},"optional":false},"year":{"schema":{"kind":"primitive","type":"number","constraint":"safe-integer"},"optional":false},"rating":{"schema":{"kind":"primitive","type":"number","constraint":"finite"},"optional":true}}}, "fixtures.typing_torture.rated_movie", __tywrapReturnDefinitions); export async function ratedMovie(): Promise { const __args: unknown[] = []; return getRuntimeBridge().call('fixtures.typing_torture', 'rated_movie', __args, undefined, __validaterated_movieResult); } -const __validateset_valuesResult = createReturnValidator({"kind":"array","element":{"kind":"primitive","type":"number"}}, "fixtures.typing_torture.set_values", __tywrapReturnDefinitions); +const __validateset_valuesResult = createReturnValidator({"kind":"array","element":{"kind":"primitive","type":"number","constraint":"safe-integer"}}, "fixtures.typing_torture.set_values", __tywrapReturnDefinitions); export async function setValues(value: number[]): Promise { const __args: unknown[] = [value]; return getRuntimeBridge().call('fixtures.typing_torture', 'set_values', __args, undefined, __validateset_valuesResult); } -const __validatetuple_key_dictResult = createReturnValidator({"kind":"record","values":{"kind":"primitive","type":"string"}}, "fixtures.typing_torture.tuple_key_dict", __tywrapReturnDefinitions); +const __validatetuple_key_dictResult = createReturnValidator({"kind":"any"}, "fixtures.typing_torture.tuple_key_dict", __tywrapReturnDefinitions); -export async function tupleKeyDict(value: Record): Promise> { +export async function tupleKeyDict(value: unknown): Promise { const __args: unknown[] = [value]; - return getRuntimeBridge().call>('fixtures.typing_torture', 'tuple_key_dict', __args, undefined, __validatetuple_key_dictResult); + return getRuntimeBridge().call('fixtures.typing_torture', 'tuple_key_dict', __args, undefined, __validatetuple_key_dictResult); } -const __validatetyped_dict_echoResult = createReturnValidator({"kind":"ref","name":"Movie"}, "fixtures.typing_torture.typed_dict_echo", __tywrapReturnDefinitions); +const __validatetyped_dict_echoResult = createReturnValidator({"kind":"record","fields":{"title":{"schema":{"kind":"primitive","type":"string"},"optional":false},"year":{"schema":{"kind":"primitive","type":"number","constraint":"safe-integer"},"optional":false}}}, "fixtures.typing_torture.typed_dict_echo", __tywrapReturnDefinitions); export async function typedDictEcho(value: Movie): Promise { const __args: unknown[] = [value]; return getRuntimeBridge().call('fixtures.typing_torture', 'typed_dict_echo', __args, undefined, __validatetyped_dict_echoResult); } -const __validateuser_id_echoResult = createReturnValidator({"kind":"any"}, "fixtures.typing_torture.user_id_echo", __tywrapReturnDefinitions); +const __validateuser_id_echoResult = createReturnValidator({"kind":"primitive","type":"number","constraint":"safe-integer"}, "fixtures.typing_torture.user_id_echo", __tywrapReturnDefinitions); export async function userIdEcho(value: UserId): Promise { const __args: unknown[] = [value]; return getRuntimeBridge().call('fixtures.typing_torture', 'user_id_echo', __args, undefined, __validateuser_id_echoResult); } -const __validatevariadic_tupleResult = createReturnValidator({"kind":"array","element":{"kind":"primitive","type":"number"}}, "fixtures.typing_torture.variadic_tuple", __tywrapReturnDefinitions); +const __validatevariadic_tupleResult = createReturnValidator({"kind":"array","element":{"kind":"primitive","type":"number","constraint":"safe-integer"}}, "fixtures.typing_torture.variadic_tuple", __tywrapReturnDefinitions); export async function variadicTuple(value: number[]): Promise { const __args: unknown[] = [value]; @@ -197,13 +194,13 @@ export function frozenValues(value: string[]): Promise; export function generatorValues(): Promise; -export function genericIdentity(value: T): Promise; +export function genericIdentity(value: T): Promise; -export function intKeyDict(value: { [key: number]: string; }): Promise<{ [key: number]: string; }>; +export function intKeyDict(value: unknown): Promise; export function iteratorValues(): Promise; -export function literalEcho(value: "red" | "blue" | 7): Promise<"red" | "blue" | 7>; +export function literalEcho(value: "red" | "blue" | 7): Promise; export function nestedContainers(value: Record[]): Promise[]>; @@ -211,17 +208,17 @@ export function noneReturn(): Promise; export function optionalUnion(value: string | number | null): Promise; -export function overloaded(value: number | string): Promise; +/* overload declarations checked separately */ -export function paramspecApply

(callback: (...args: P) => T, args?: unknown[], kwargs?: Record): Promise; +export function paramspecApply

(callback: (...args: P) => T, args?: unknown[], kwargs?: Record): Promise; -export function protocolIdentity(value: SupportsClose): Promise; +export function protocolIdentity(value: SupportsClose): Promise; export function ratedMovie(): Promise; export function setValues(value: number[]): Promise; -export function tupleKeyDict(value: Record): Promise>; +export function tupleKeyDict(value: unknown): Promise; export function typedDictEcho(value: Movie): Promise; @@ -256,7 +253,7 @@ import { createReturnValidator, getRuntimeBridge, type ReturnSchema } from 'tywr const __tywrapReturnDefinitions: Record = {}; -const __validatebools_and_intsResult = createReturnValidator({"kind":"array","element":{"kind":"union","options":[{"kind":"primitive","type":"boolean"},{"kind":"primitive","type":"number"}]}}, "fixtures.values_torture.bools_and_ints", __tywrapReturnDefinitions); +const __validatebools_and_intsResult = createReturnValidator({"kind":"array","element":{"kind":"union","options":[{"kind":"primitive","type":"boolean"},{"kind":"primitive","type":"number","constraint":"safe-integer"}]}}, "fixtures.values_torture.bools_and_ints", __tywrapReturnDefinitions); export async function boolsAndInts(): Promise { const __args: unknown[] = []; @@ -286,26 +283,26 @@ export async function coroutineValue(): Promise { const __validatedataclass_instanceResult = createReturnValidator({"kind":"any"}, "fixtures.values_torture.dataclass_instance", __tywrapReturnDefinitions); -export async function dataclassInstance(): Promise { +export async function dataclassInstance(): Promise { const __args: unknown[] = []; - return getRuntimeBridge().call('fixtures.values_torture', 'dataclass_instance', __args, undefined, __validatedataclass_instanceResult); + return getRuntimeBridge().call('fixtures.values_torture', 'dataclass_instance', __args, undefined, __validatedataclass_instanceResult); } const __validatedecimal_valuesResult = createReturnValidator({"kind":"array","element":{"kind":"any"}}, "fixtures.values_torture.decimal_values", __tywrapReturnDefinitions); -export async function decimalValues(): Promise { +export async function decimalValues(): Promise { const __args: unknown[] = []; - return getRuntimeBridge().call('fixtures.values_torture', 'decimal_values', __args, undefined, __validatedecimal_valuesResult); + return getRuntimeBridge().call('fixtures.values_torture', 'decimal_values', __args, undefined, __validatedecimal_valuesResult); } const __validatedeeply_nestedResult = createReturnValidator({"kind":"array","element":{"kind":"any"}}, "fixtures.values_torture.deeply_nested", __tywrapReturnDefinitions); -export async function deeplyNested(): Promise { +export async function deeplyNested(): Promise { const __args: unknown[] = []; - return getRuntimeBridge().call('fixtures.values_torture', 'deeply_nested', __args, undefined, __validatedeeply_nestedResult); + return getRuntimeBridge().call('fixtures.values_torture', 'deeply_nested', __args, undefined, __validatedeeply_nestedResult); } -const __validateecho_intResult = createReturnValidator({"kind":"primitive","type":"number"}, "fixtures.values_torture.echo_int", __tywrapReturnDefinitions); +const __validateecho_intResult = createReturnValidator({"kind":"primitive","type":"number","constraint":"safe-integer"}, "fixtures.values_torture.echo_int", __tywrapReturnDefinitions); export async function echoInt(value: number): Promise { const __args: unknown[] = [value]; @@ -314,9 +311,9 @@ export async function echoInt(value: number): Promise { const __validateempty_valuesResult = createReturnValidator({"kind":"tuple","elements":[{"kind":"tuple","elements":[{"kind":"any"}]},{"kind":"array","element":{"kind":"any"}},{"kind":"record","values":{"kind":"any"}},{"kind":"array","element":{"kind":"any"}}]}, "fixtures.values_torture.empty_values", __tywrapReturnDefinitions); -export async function emptyValues(): Promise<[[unknown], object[], Record, object[]]> { +export async function emptyValues(): Promise { const __args: unknown[] = []; - return getRuntimeBridge().call<[[unknown], object[], Record, object[]]>('fixtures.values_torture', 'empty_values', __args, undefined, __validateempty_valuesResult); + return getRuntimeBridge().call('fixtures.values_torture', 'empty_values', __args, undefined, __validateempty_valuesResult); } const __validateenum_memberResult = createReturnValidator({"kind":"any"}, "fixtures.values_torture.enum_member", __tywrapReturnDefinitions); @@ -326,7 +323,7 @@ export async function enumMember(): Promise { return getRuntimeBridge().call('fixtures.values_torture', 'enum_member', __args, undefined, __validateenum_memberResult); } -const __validatefinite_float_edgesResult = createReturnValidator({"kind":"array","element":{"kind":"primitive","type":"number"}}, "fixtures.values_torture.finite_float_edges", __tywrapReturnDefinitions); +const __validatefinite_float_edgesResult = createReturnValidator({"kind":"array","element":{"kind":"primitive","type":"number","constraint":"finite"}}, "fixtures.values_torture.finite_float_edges", __tywrapReturnDefinitions); export async function finiteFloatEdges(): Promise { const __args: unknown[] = []; @@ -335,61 +332,61 @@ export async function finiteFloatEdges(): Promise { const __validategenerator_valueResult = createReturnValidator({"kind":"any"}, "fixtures.values_torture.generator_value", __tywrapReturnDefinitions); -export async function generatorValue(): Promise { +export async function generatorValue(): Promise { const __args: unknown[] = []; - return getRuntimeBridge().call('fixtures.values_torture', 'generator_value', __args, undefined, __validategenerator_valueResult); + return getRuntimeBridge().call('fixtures.values_torture', 'generator_value', __args, undefined, __validategenerator_valueResult); } -const __validateint_key_dictResult = createReturnValidator({"kind":"record","values":{"kind":"primitive","type":"string"}}, "fixtures.values_torture.int_key_dict", __tywrapReturnDefinitions); +const __validateint_key_dictResult = createReturnValidator({"kind":"any"}, "fixtures.values_torture.int_key_dict", __tywrapReturnDefinitions); -export async function intKeyDict(): Promise<{ [key: number]: string; }> { +export async function intKeyDict(): Promise { const __args: unknown[] = []; - return getRuntimeBridge().call<{ [key: number]: string; }>('fixtures.values_torture', 'int_key_dict', __args, undefined, __validateint_key_dictResult); + return getRuntimeBridge().call('fixtures.values_torture', 'int_key_dict', __args, undefined, __validateint_key_dictResult); } -const __validateinteger_boundariesResult = createReturnValidator({"kind":"array","element":{"kind":"primitive","type":"number"}}, "fixtures.values_torture.integer_boundaries", __tywrapReturnDefinitions); +const __validateinteger_boundariesResult = createReturnValidator({"kind":"array","element":{"kind":"primitive","type":"number","constraint":"safe-integer"}}, "fixtures.values_torture.integer_boundaries", __tywrapReturnDefinitions); export async function integerBoundaries(): Promise { const __args: unknown[] = []; return getRuntimeBridge().call('fixtures.values_torture', 'integer_boundaries', __args, undefined, __validateinteger_boundariesResult); } -const __validateinteger_factorial_30Result = createReturnValidator({"kind":"primitive","type":"number"}, "fixtures.values_torture.integer_factorial_30", __tywrapReturnDefinitions); +const __validateinteger_factorial_30Result = createReturnValidator({"kind":"primitive","type":"number","constraint":"safe-integer"}, "fixtures.values_torture.integer_factorial_30", __tywrapReturnDefinitions); export async function integerFactorial_30(): Promise { const __args: unknown[] = []; return getRuntimeBridge().call('fixtures.values_torture', 'integer_factorial_30', __args, undefined, __validateinteger_factorial_30Result); } -const __validateinteger_first_roundedResult = createReturnValidator({"kind":"primitive","type":"number"}, "fixtures.values_torture.integer_first_rounded", __tywrapReturnDefinitions); +const __validateinteger_first_roundedResult = createReturnValidator({"kind":"primitive","type":"number","constraint":"safe-integer"}, "fixtures.values_torture.integer_first_rounded", __tywrapReturnDefinitions); export async function integerFirstRounded(): Promise { const __args: unknown[] = []; return getRuntimeBridge().call('fixtures.values_torture', 'integer_first_rounded', __args, undefined, __validateinteger_first_roundedResult); } -const __validateinteger_first_unsafeResult = createReturnValidator({"kind":"primitive","type":"number"}, "fixtures.values_torture.integer_first_unsafe", __tywrapReturnDefinitions); +const __validateinteger_first_unsafeResult = createReturnValidator({"kind":"primitive","type":"number","constraint":"safe-integer"}, "fixtures.values_torture.integer_first_unsafe", __tywrapReturnDefinitions); export async function integerFirstUnsafe(): Promise { const __args: unknown[] = []; return getRuntimeBridge().call('fixtures.values_torture', 'integer_first_unsafe', __args, undefined, __validateinteger_first_unsafeResult); } -const __validateinteger_int64_maxResult = createReturnValidator({"kind":"primitive","type":"number"}, "fixtures.values_torture.integer_int64_max", __tywrapReturnDefinitions); +const __validateinteger_int64_maxResult = createReturnValidator({"kind":"primitive","type":"number","constraint":"safe-integer"}, "fixtures.values_torture.integer_int64_max", __tywrapReturnDefinitions); export async function integerInt64Max(): Promise { const __args: unknown[] = []; return getRuntimeBridge().call('fixtures.values_torture', 'integer_int64_max', __args, undefined, __validateinteger_int64_maxResult); } -const __validateinteger_int64_minResult = createReturnValidator({"kind":"primitive","type":"number"}, "fixtures.values_torture.integer_int64_min", __tywrapReturnDefinitions); +const __validateinteger_int64_minResult = createReturnValidator({"kind":"primitive","type":"number","constraint":"safe-integer"}, "fixtures.values_torture.integer_int64_min", __tywrapReturnDefinitions); export async function integerInt64Min(): Promise { const __args: unknown[] = []; return getRuntimeBridge().call('fixtures.values_torture', 'integer_int64_min', __args, undefined, __validateinteger_int64_minResult); } -const __validateinteger_safe_maxResult = createReturnValidator({"kind":"primitive","type":"number"}, "fixtures.values_torture.integer_safe_max", __tywrapReturnDefinitions); +const __validateinteger_safe_maxResult = createReturnValidator({"kind":"primitive","type":"number","constraint":"safe-integer"}, "fixtures.values_torture.integer_safe_max", __tywrapReturnDefinitions); export async function integerSafeMax(): Promise { const __args: unknown[] = []; @@ -410,14 +407,14 @@ export async function megabyteText(): Promise { return getRuntimeBridge().call('fixtures.values_torture', 'megabyte_text', __args, undefined, __validatemegabyte_textResult); } -const __validateset_and_frozensetResult = createReturnValidator({"kind":"tuple","elements":[{"kind":"array","element":{"kind":"primitive","type":"number"}},{"kind":"array","element":{"kind":"primitive","type":"string"}}]}, "fixtures.values_torture.set_and_frozenset", __tywrapReturnDefinitions); +const __validateset_and_frozensetResult = createReturnValidator({"kind":"tuple","elements":[{"kind":"array","element":{"kind":"primitive","type":"number","constraint":"safe-integer"}},{"kind":"array","element":{"kind":"primitive","type":"string"}}]}, "fixtures.values_torture.set_and_frozenset", __tywrapReturnDefinitions); export async function setAndFrozenset(): Promise<[number[], string[]]> { const __args: unknown[] = []; return getRuntimeBridge().call<[number[], string[]]>('fixtures.values_torture', 'set_and_frozenset', __args, undefined, __validateset_and_frozensetResult); } -const __validatespecial_floatsResult = createReturnValidator({"kind":"array","element":{"kind":"primitive","type":"number"}}, "fixtures.values_torture.special_floats", __tywrapReturnDefinitions); +const __validatespecial_floatsResult = createReturnValidator({"kind":"array","element":{"kind":"primitive","type":"number","constraint":"finite"}}, "fixtures.values_torture.special_floats", __tywrapReturnDefinitions); export function specialFloats(): Promise; export function specialFloats(include?: boolean): Promise; @@ -431,16 +428,16 @@ export async function specialFloats(include?: boolean): Promise { const __validatetemporal_valuesResult = createReturnValidator({"kind":"record","values":{"kind":"any"}}, "fixtures.values_torture.temporal_values", __tywrapReturnDefinitions); -export async function temporalValues(): Promise> { +export async function temporalValues(): Promise { const __args: unknown[] = []; - return getRuntimeBridge().call>('fixtures.values_torture', 'temporal_values', __args, undefined, __validatetemporal_valuesResult); + return getRuntimeBridge().call('fixtures.values_torture', 'temporal_values', __args, undefined, __validatetemporal_valuesResult); } -const __validatetuple_key_dictResult = createReturnValidator({"kind":"record","values":{"kind":"primitive","type":"string"}}, "fixtures.values_torture.tuple_key_dict", __tywrapReturnDefinitions); +const __validatetuple_key_dictResult = createReturnValidator({"kind":"any"}, "fixtures.values_torture.tuple_key_dict", __tywrapReturnDefinitions); -export async function tupleKeyDict(): Promise> { +export async function tupleKeyDict(): Promise { const __args: unknown[] = []; - return getRuntimeBridge().call>('fixtures.values_torture', 'tuple_key_dict', __args, undefined, __validatetuple_key_dictResult); + return getRuntimeBridge().call('fixtures.values_torture', 'tuple_key_dict', __args, undefined, __validatetuple_key_dictResult); } const __validateunicode_textResult = createReturnValidator({"kind":"primitive","type":"string"}, "fixtures.values_torture.unicode_text", __tywrapReturnDefinitions); @@ -452,9 +449,9 @@ export async function unicodeText(): Promise { const __validateuuid_and_pathResult = createReturnValidator({"kind":"record","values":{"kind":"any"}}, "fixtures.values_torture.uuid_and_path", __tywrapReturnDefinitions); -export async function uuidAndPath(): Promise> { +export async function uuidAndPath(): Promise { const __args: unknown[] = []; - return getRuntimeBridge().call>('fixtures.values_torture', 'uuid_and_path', __args, undefined, __validateuuid_and_pathResult); + return getRuntimeBridge().call('fixtures.values_torture', 'uuid_and_path', __args, undefined, __validateuuid_and_pathResult); } /** @@ -482,23 +479,23 @@ export function complexValue(): Promise; export function coroutineValue(): Promise; -export function dataclassInstance(): Promise; +export function dataclassInstance(): Promise; -export function decimalValues(): Promise; +export function decimalValues(): Promise; -export function deeplyNested(): Promise; +export function deeplyNested(): Promise; export function echoInt(value: number): Promise; -export function emptyValues(): Promise<[[unknown], object[], Record, object[]]>; +export function emptyValues(): Promise; export function enumMember(): Promise; export function finiteFloatEdges(): Promise; -export function generatorValue(): Promise; +export function generatorValue(): Promise; -export function intKeyDict(): Promise<{ [key: number]: string; }>; +export function intKeyDict(): Promise; export function integerBoundaries(): Promise; @@ -523,13 +520,13 @@ export function setAndFrozenset(): Promise<[number[], string[]]>; export function specialFloats(): Promise; export function specialFloats(include?: boolean): Promise; -export function temporalValues(): Promise>; +export function temporalValues(): Promise; -export function tupleKeyDict(): Promise>; +export function tupleKeyDict(): Promise; export function unicodeText(): Promise; -export function uuidAndPath(): Promise>; +export function uuidAndPath(): Promise; /** * Point(x: 'int', y: 'int') diff --git a/test/menagerie/fixtures/library_torture.py b/test/menagerie/fixtures/library_torture.py index 502bcd1d..7d705d56 100644 --- a/test/menagerie/fixtures/library_torture.py +++ b/test/menagerie/fixtures/library_torture.py @@ -23,6 +23,16 @@ def numpy_adversarial() -> object: } +def numpy_adversarial_safe_scalar() -> object: + import numpy as np + + return { + "array": np.array([2**53 + 1, 2**63 - 1], dtype=np.int64), + "scalar": np.int64(2**53 - 1), + "float_column": np.array([1.0, 2.5]), + } + + def pandas_adversarial() -> object: import pandas as pd @@ -345,6 +355,16 @@ def sklearn_simple_estimator() -> object: return LinearRegression(fit_intercept=False, positive=True) +def sklearn_unsafe_nested_estimator() -> object: + from sklearn.base import BaseEstimator + + class NestedParams(BaseEstimator): + def __init__(self, config: object = None): + self.config = config + + return NestedParams(config={'nested': {'unsafe': 2**53 + 1}}) + + def sklearn_pipeline() -> object: from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline diff --git a/test/menagerie/fixtures/torch_callable.py b/test/menagerie/fixtures/torch_callable.py new file mode 100644 index 00000000..1d968ca6 --- /dev/null +++ b/test/menagerie/fixtures/torch_callable.py @@ -0,0 +1,11 @@ +"""Real CPU tensor returns for generated Torch float16 checks.""" + +import torch + + +def half_values() -> torch.HalfTensor: + return torch.tensor([1.5, -2.25, -0.0], dtype=torch.float16) + + +def wrong_half_values() -> torch.HalfTensor: + return torch.tensor([1.5, -2.25], dtype=torch.float32) diff --git a/test/menagerie/gen.test.ts b/test/menagerie/gen.test.ts index 204495be..d40160ca 100644 --- a/test/menagerie/gen.test.ts +++ b/test/menagerie/gen.test.ts @@ -9,6 +9,14 @@ import { TIER_ONE_MODULES } from './manifest.js'; const defaultPythonPath = getDefaultPythonPath(); const fixtureImportPath = 'test/menagerie'; +async function supportsPythonOverloads(): Promise { + const result = await processUtils.exec(defaultPythonPath, [ + '-c', + 'import typing; raise SystemExit(0 if hasattr(typing, "get_overloads") else 1)', + ]); + return result.code === 0; +} + async function compileGeneratedFile(generatedPath: string): Promise { const tscPath = join(process.cwd(), 'node_modules', 'typescript', 'lib', 'tsc.js'); const compile = await processUtils.exec( @@ -60,12 +68,40 @@ describe('menagerie generation gate', () => { expect(generatedTs).toBeDefined(); expect(generatedDeclaration).toBeDefined(); - await expect( - Promise.all([ - fsUtils.readFile(generatedTs as string), - fsUtils.readFile(generatedDeclaration as string), - ]) - ).resolves.toMatchSnapshot(); + let generated = await Promise.all([ + fsUtils.readFile(generatedTs as string), + fsUtils.readFile(generatedDeclaration as string), + ]); + if (moduleName === 'fixtures.typing_torture') { + const supportsOverloads = await supportsPythonOverloads(); + if (supportsOverloads) { + expect(generated[0]).toContain('selectOverloadReturnValidator('); + expect(generated[1]).toContain('export function overloaded(value: number)'); + expect(generated[1]).toContain('export function overloaded(value: string)'); + } else { + expect(generated[0]).toContain( + 'export async function overloaded(value: number | string)' + ); + expect(generated[1]).toContain('export function overloaded(value: number | string)'); + await compileGeneratedFile(generatedTs as string); + } + generated = [ + generated[0] + .replace( + 'createReturnValidator, selectOverloadReturnValidator, getRuntimeBridge', + 'createReturnValidator, getRuntimeBridge' + ) + .replace( + /^(?:export function overloaded[^\n]*\n)*export async function overloaded[^\n]*\n[\s\S]*?^\}/m, + '/* overload implementation checked separately */' + ), + generated[1].replace( + /^export function overloaded[^\n]*(?:\nexport function overloaded[^\n]*)*/m, + '/* overload declarations checked separately */' + ), + ]; + } + expect(generated).toMatchSnapshot(); } finally { await rm(tempDir, { recursive: true, force: true }); } diff --git a/test/menagerie/libs.test.ts b/test/menagerie/libs.test.ts index 1a8a3bc8..25e51f19 100644 --- a/test/menagerie/libs.test.ts +++ b/test/menagerie/libs.test.ts @@ -63,17 +63,20 @@ describe.skipIf(!bridgeAvailable)('menagerie optional-library gate', () => { ); it.skipIf(!hasPythonModule('numpy') || !hasPythonModule('pyarrow'))( - 'round-trips ndarrays nested in a mapping while retaining scalar behavior', + 'preserves nested Arrow arrays and rejects unsafe NumPy scalars', async () => { const bridge = makeBridge(); try { await expect( - bridge.call('fixtures.library_torture', 'numpy_adversarial', []) + bridge.call('fixtures.library_torture', 'numpy_adversarial_safe_scalar', []) ).resolves.toEqual({ array: [9007199254740993n, 9223372036854775807n], - scalar: 9007199254740992, + scalar: 9007199254740991, float_column: [1, 2.5], }); + await expect( + bridge.call('fixtures.library_torture', 'numpy_adversarial', []) + ).rejects.toThrow(/Unsafe Python integer at result\.scalar/); } finally { await bridge.dispose(); } diff --git a/test/menagerie/manifest.ts b/test/menagerie/manifest.ts index b40368fa..61330512 100644 --- a/test/menagerie/manifest.ts +++ b/test/menagerie/manifest.ts @@ -134,42 +134,37 @@ export const RUNTIME_CATALOGUE: readonly CatalogueRow[] = [ valuesRow({ id: 'integer-first-unsafe', call: 'integer_first_unsafe()', - status: 'KNOWN_LIE', - currentBehavior: 'The first unsafe integer is delivered as an untagged JavaScript number.', - expected: equal(2 ** 53), - expectedFix: 'Future bigint or tagged-integer transport.', + status: 'LOUD_FAIL', + currentBehavior: 'The bridge rejects the first unsafe integer before JSON encoding.', + expected: error(/Unsafe Python integer at result:.*outside the JavaScript safe integer range/i), }), valuesRow({ id: 'integer-first-rounded', call: 'integer_first_rounded()', - status: 'KNOWN_LIE', - currentBehavior: '2^53 + 1 rounds down to 2^53 in JavaScript.', - expected: equal(2 ** 53), - expectedFix: 'Future bigint or tagged-integer transport.', + status: 'LOUD_FAIL', + currentBehavior: 'The bridge rejects 2^53 + 1 before JSON encoding.', + expected: error(/Unsafe Python integer at result:.*outside the JavaScript safe integer range/i), }), valuesRow({ id: 'integer-int64-max', call: 'integer_int64_max()', - status: 'KNOWN_LIE', - currentBehavior: 'The signed int64 maximum rounds in JavaScript.', - expected: equal(2 ** 63), - expectedFix: 'Future bigint or tagged-integer transport.', + status: 'LOUD_FAIL', + currentBehavior: 'The bridge rejects the signed int64 maximum before JSON encoding.', + expected: error(/Unsafe Python integer at result:.*outside the JavaScript safe integer range/i), }), valuesRow({ id: 'integer-int64-min', call: 'integer_int64_min()', - status: 'KNOWN_LIE', - currentBehavior: 'The signed int64 minimum is delivered as an unsafe JavaScript number.', - expected: equal(-(2 ** 63)), - expectedFix: 'Future bigint or tagged-integer transport.', + status: 'LOUD_FAIL', + currentBehavior: 'The bridge rejects the signed int64 minimum before JSON encoding.', + expected: error(/Unsafe Python integer at result:.*outside the JavaScript safe integer range/i), }), valuesRow({ id: 'integer-factorial-30', call: 'integer_factorial_30()', - status: 'KNOWN_LIE', - currentBehavior: 'factorial(30) is delivered as a rounded JavaScript number.', - expected: equal(2.6525285981219107e32), - expectedFix: 'Future bigint or tagged-integer transport.', + status: 'LOUD_FAIL', + currentBehavior: 'The bridge rejects factorial(30) before JSON encoding.', + expected: error(/Unsafe Python integer at result:.*outside the JavaScript safe integer range/i), }), valuesRow({ id: 'empty-values', @@ -246,10 +241,9 @@ export const RUNTIME_CATALOGUE: readonly CatalogueRow[] = [ ['special-floats', 'special_floats(true)', 'special_floats', [true], /NaN|Infinity|serialize/i], ['tuple-key-dict', 'tuple_key_dict()', 'tuple_key_dict', [], /keys must be str/i], ['enum-member', 'enum_member()', 'enum_member', [], /TrafficLight|serializable/i], - ['coroutine-value', 'coroutine_value()', 'coroutine_value', [], /coroutine|serializable/i], ['dataclass-instance', 'dataclass_instance()', 'dataclass_instance', [], /serializable/i], ['complex-value', 'complex_value()', 'complex_value', [], /serializable/i], - ['generator-value', 'generator_value()', 'generator_value', [], /serializable/i], + ['generator-value', 'generator_value()', 'generator_value', [], /generator|supported/i], ].map(([id, call, functionName, args, pattern]) => valuesRow({ id: id as string, @@ -261,6 +255,13 @@ export const RUNTIME_CATALOGUE: readonly CatalogueRow[] = [ expected: error(pattern as RegExp), }) ), + valuesRow({ + id: 'coroutine-value', + call: 'coroutine_value()', + status: 'EXPECTED_OK', + currentBehavior: 'The bridge awaits the coroutine and returns its string result.', + expected: equal('coroutine-result'), + }), // NumPy: Arrow is the default subprocess path; JSON rows pin fallback-only differences. libraryRow({ @@ -286,9 +287,9 @@ export const RUNTIME_CATALOGUE: readonly CatalogueRow[] = [ call: 'numpy_float16()', codec: 'arrow', requires: ['numpy', 'pyarrow'], - status: 'KNOWN_LIE', - currentBehavior: 'Arrow JS exposes float16 storage bits as numbers.', - expected: equal([15872, 49280]), + status: 'EXPECTED_OK', + currentBehavior: 'Arrow float16 storage bits decode to numeric values.', + expected: { kind: 'ndarray', value: [1.5, -2.25], dtype: 'float16' }, }), libraryRow({ id: 'numpy-float16-json', @@ -745,13 +746,12 @@ export const RUNTIME_CATALOGUE: readonly CatalogueRow[] = [ call: 'torch_float16()', codec: 'arrow', requires: ['torch', 'pyarrow'], - status: 'KNOWN_LIE', - currentBehavior: 'Arrow JS exposes float16 tensor storage bits as numbers.', + status: 'EXPECTED_OK', + currentBehavior: 'The nested ndarray converts float16 tensor storage to numeric values.', expected: { kind: 'match', - value: { data: [15872, 49280], shape: [2], dtype: 'torch.float16', device: 'cpu' }, + value: { data: [1.5, -2.25], shape: [2], dtype: 'torch.float16', device: 'cpu' }, }, - expectedFix: 'Future Arrow float16 decoding that preserves numeric values.', }), libraryRow({ id: 'torch-float16-json', @@ -876,6 +876,14 @@ export const RUNTIME_CATALOGUE: readonly CatalogueRow[] = [ value: { className: 'LinearRegression', params: { fit_intercept: false, positive: true } }, }, }), + libraryRow({ + id: 'sklearn-unsafe-nested-estimator', + call: 'sklearn_unsafe_nested_estimator()', + requires: ['sklearn'], + status: 'LOUD_FAIL', + currentBehavior: 'Unsafe nested estimator parameters reject before JSON encoding.', + expected: error(/Unsafe Python integer at result\.params\.config\.nested\.unsafe/), + }), libraryRow({ id: 'sklearn-pipeline', call: 'sklearn_pipeline()', diff --git a/test/menagerie/torch_callable.test.ts b/test/menagerie/torch_callable.test.ts new file mode 100644 index 00000000..19316ca1 --- /dev/null +++ b/test/menagerie/torch_callable.test.ts @@ -0,0 +1,197 @@ +import { execFile } from 'node:child_process'; +import { delimiter, basename, join } from 'node:path'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { promisify } from 'node:util'; + +import { describe, expect, it } from 'vitest'; + +import { generate } from '../../src/tywrap.js'; +import { hasPythonModule, PYTHON, PYTHON_AVAILABLE } from '../helpers/python-probe.js'; + +const execFileAsync = promisify(execFile); +const repoRoot = process.cwd(); +const fixtureRoot = join(repoRoot, 'test', 'menagerie'); +const required = process.env.TYWRAP_REQUIRE_TORCH_CONFORMANCE === '1'; +const available = PYTHON_AVAILABLE && hasPythonModule('torch') && hasPythonModule('pyarrow'); + +async function run(command: string, args: string[], cwd: string, env?: NodeJS.ProcessEnv) { + try { + return await execFileAsync(command, args, { + cwd, + env, + timeout: 90_000, + maxBuffer: 4 * 1024 * 1024, + }); + } catch (error: unknown) { + const result = error as { stdout?: string; stderr?: string; message?: string }; + throw new Error( + `${command} ${args.join(' ')} failed: ${result.stderr ?? result.stdout ?? result.message ?? 'unknown error'}` + ); + } +} + +describe('real Torch generated callable', () => { + it.skipIf(!required && !available)( + 'analyzes, typechecks, executes, and rejects a wrong CPU float16 return', + async () => { + if (!available || !PYTHON) { + throw new Error('The required scientific CI job needs Python, Torch, and PyArrow'); + } + const tempRoot = await mkdtemp(join(repoRoot, '.tmp-menagerie-torch-')); + const pythonEnv = { + ...process.env, + PYTHONPATH: process.env.PYTHONPATH + ? `${fixtureRoot}${delimiter}${process.env.PYTHONPATH}` + : fixtureRoot, + }; + try { + const analyzed = await run( + PYTHON, + [ + '-c', + 'import json; from tywrap_ir.ir import extract_module_ir; ir=extract_module_ir("fixtures.torch_callable"); print(json.dumps({"functions": [{"name": f["name"], "returns": f["returns"]} for f in ir["functions"]], "warnings": ir["warnings"]}))', + ], + tempRoot, + pythonEnv + ); + const ir = JSON.parse(analyzed.stdout) as { + functions: { name: string; returns: string }[]; + warnings: string[]; + }; + expect(ir.functions).toEqual([ + { name: 'half_values', returns: 'torch.HalfTensor' }, + { name: 'wrong_half_values', returns: 'torch.HalfTensor' }, + ]); + expect(ir.warnings).toEqual([ + 'Return annotation for fixtures.torch_callable.half_values resolves outside analyzed module: torch.HalfTensor.', + 'Return annotation for fixtures.torch_callable.wrong_half_values resolves outside analyzed module: torch.HalfTensor.', + ]); + + const generatedDir = join(tempRoot, 'generated'); + const generated = await generate({ + pythonModules: { + 'fixtures.torch_callable': { runtime: 'node', typeHints: 'strict' }, + }, + pythonImportPath: [fixtureRoot], + output: { dir: generatedDir, format: 'esm', declaration: true, sourceMap: false }, + runtime: { node: { pythonPath: PYTHON } }, + performance: { caching: false, batching: false, compression: 'none' }, + } as never); + expect(generated.failures).toEqual([]); + expect(generated.warnings).toEqual([]); + const generatedTs = generated.written.find(path => path.endsWith('.generated.ts')); + expect(generatedTs).toBeDefined(); + const source = await readFile(generatedTs as string, 'utf8'); + expect(source).toContain('"marker":"torch.tensor","dtype":"torch.float16"'); + + const generatedJs = basename(generatedTs as string).replace(/\.ts$/, '.js'); + const typecheckPath = join(tempRoot, 'torch.typecheck.ts'); + await writeFile( + typecheckPath, + `import { halfValues, wrongHalfValues } from './generated/${generatedJs}'; +type Float16Value = number | Float16Value[]; +type Float16Tensor = { data: Float16Value; shape: number[]; dtype: 'torch.float16'; device?: string }; +const good: Promise = halfValues(); +const declaredWrong: Promise = wrongHalfValues(); +type GeneratedTensor = Awaited>; +const dtype: GeneratedTensor['dtype'] = 'torch.float16'; +// @ts-expect-error A float32 dtype cannot satisfy the generated return type. +const wrongDtype: GeneratedTensor['dtype'] = 'torch.float32'; +void good; +void declaredWrong; +void dtype; +void wrongDtype; +`, + 'utf8' + ); + await run( + process.execPath, + [ + join(repoRoot, 'node_modules', 'typescript', 'lib', 'tsc.js'), + '--ignoreConfig', + '--target', + 'ES2022', + '--module', + 'NodeNext', + '--moduleResolution', + 'NodeNext', + '--strict', + '--skipLibCheck', + '--rootDir', + tempRoot, + '--outDir', + join(tempRoot, 'built'), + generatedTs as string, + typecheckPath, + ], + repoRoot + ); + + const runnerPath = join(tempRoot, 'run-torch.mjs'); + await writeFile( + runnerPath, + `import { BridgeValidationError } from 'tywrap'; +import { NodeBridge } from 'tywrap/node'; +import { clearRuntimeBridge, setRuntimeBridge } from 'tywrap/runtime'; +import * as fixture from './built/generated/${generatedJs}'; + +const [pythonPath, fixtureRoot] = process.argv.slice(2); +const bridge = new NodeBridge({ + pythonPath, + cwd: process.cwd(), + env: { + PYTHONNOUSERSITE: '1', + PYTHONPATH: fixtureRoot, + TYWRAP_ALLOWED_MODULES: 'fixtures.torch_callable', + }, +}); +try { + setRuntimeBridge({ call: bridge.call.bind(bridge), dispose: bridge.dispose.bind(bridge) }); + const value = await fixture.halfValues(); + if (value.dtype !== 'torch.float16' || value.device !== 'cpu' || + JSON.stringify(value.shape) !== '[3]' || + JSON.stringify(value.data) !== '[1.5,-2.25,0]' || + !Object.is(value.data[2], -0)) { + throw new Error('The generated Torch wrapper did not return CPU float16 values'); + } + let wrongError; + try { + await fixture.wrongHalfValues(); + } catch (error) { + wrongError = error; + } + if (!(wrongError instanceof BridgeValidationError) || + wrongError.callSite !== 'fixtures.torch_callable.wrong_half_values') { + throw new Error('The generated return validator accepted a float32 tensor'); + } + process.stdout.write(JSON.stringify({ + dtype: value.dtype, + shape: value.shape, + data: value.data, + device: value.device, + negativeZero: Object.is(value.data[2], -0), + wrongError: wrongError.name, + })); +} finally { + clearRuntimeBridge(); + await bridge.dispose(); +} +`, + 'utf8' + ); + const execution = await run(process.execPath, [runnerPath, PYTHON, fixtureRoot], repoRoot); + expect(JSON.parse(execution.stdout)).toEqual({ + dtype: 'torch.float16', + shape: [3], + data: [1.5, -2.25, 0], + device: 'cpu', + negativeZero: true, + wrongError: 'BridgeValidationError', + }); + } finally { + await rm(tempRoot, { recursive: true, force: true }); + } + }, + 120_000 + ); +}); diff --git a/test/prototypes/value_contract_v3_adapter.ts b/test/prototypes/value_contract_v3_adapter.ts new file mode 100644 index 00000000..17f9eb73 --- /dev/null +++ b/test/prototypes/value_contract_v3_adapter.ts @@ -0,0 +1,19 @@ +/** Translate resolved v3 nodes into the isolated cross-language test codec. */ + +import type { ValueContractV3 } from '../../src/contracts/value-contract.js'; +import type { PrototypeContract } from './value_extensions.js'; + +export function toExactPrototypeContract(value: ValueContractV3): PrototypeContract { + switch (value.kind) { + case 'integer-exact': + return { kind: 'integer' }; + case 'boolean': + return { kind: 'boolean' }; + case 'float': + return { kind: 'float' }; + case 'sequence': + return { kind: 'array', item: toExactPrototypeContract(value.item) }; + default: + throw new Error(`The exact call fixture cannot use ${value.kind}.`); + } +} diff --git a/test/prototypes/value_exact_call.py b/test/prototypes/value_exact_call.py new file mode 100644 index 00000000..fae0cdc4 --- /dev/null +++ b/test/prototypes/value_exact_call.py @@ -0,0 +1,63 @@ +"""Private Python call adapter for the exact-integer compiler proof.""" + +from __future__ import annotations + +import json +import sys +from typing import Any + +from value_contract_exact_integer import combine_exact, echo_exact +from value_extensions import ( + MAX_PAYLOAD_BYTES, + PrototypeError, + decode_exact_integers, + encode_exact_integers, + require_capability, +) + + +def main() -> None: + trusted_contract: dict[str, Any] = json.loads(sys.argv[1]) + bridge_meta: dict[str, Any] = json.loads(sys.argv[2]) + function_name = sys.argv[3] + functions = {'combine_exact': combine_exact, 'echo_exact': echo_exact} + function = functions.get(function_name) + if function is None: + raise PrototypeError('unknown exact-integer callable') + raw = sys.stdin.buffer.read(MAX_PAYLOAD_BYTES + 1) + if len(raw) > MAX_PAYLOAD_BYTES: + raise PrototypeError('input payload exceeds byte limit') + request: dict[str, Any] = json.loads(raw) + if (request.get('module'), request.get('functionName')) != ( + 'value_contract_exact_integer', + function_name, + ): + raise PrototypeError('unexpected exact-integer callable') + params = request.get('params') + if not isinstance(params, dict): + raise PrototypeError('missing exact-integer call parameters') + value_policy = params.get('valuePolicy') + policy = value_policy.get('integer') if isinstance(value_policy, dict) else None + require_capability(bridge_meta, 'exactIntegerDecimalV2', policy) + args = params.get('args') + fields = trusted_contract.get('fields') + if ( + trusted_contract.get('kind') != 'record' + or not isinstance(fields, dict) + or not isinstance(args, list) + or len(args) != len(fields) + ): + raise PrototypeError('exact-integer arguments differ from the contract') + input_record = dict(zip(fields, args, strict=True)) + decoded = decode_exact_integers(input_record, trusted_contract) + assert isinstance(decoded, dict) + result = function(**decoded) + encoded = encode_exact_integers(result) + wire = json.dumps( + encoded, allow_nan=False, ensure_ascii=False, separators=(',', ':') + ).encode('utf-8') + sys.stdout.buffer.write(wire + b'\n') + + +if __name__ == '__main__': + main() diff --git a/test/prototypes/value_extensions.py b/test/prototypes/value_extensions.py new file mode 100644 index 00000000..135c519b --- /dev/null +++ b/test/prototypes/value_extensions.py @@ -0,0 +1,391 @@ +"""Isolated wire prototypes for #337 and #339. Production never imports this file.""" + +from __future__ import annotations + +import dataclasses +import json +import math +import re +import sys +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any + + +MAX_DECIMAL_DIGITS = 4096 +MAX_DEPTH = 64 +MAX_NODES = 100_000 +MAX_PAYLOAD_BYTES = 10 * 1024 * 1024 +SAFE_INTEGER_MAX = 2**53 - 1 +MAX_INTEGER_MAGNITUDE = 10**MAX_DECIMAL_DIGITS +DECIMAL = re.compile(r'(?:0|[1-9][0-9]*|-[1-9][0-9]*)\Z', re.ASCII) +INTEGER_FIELDS = frozenset({'__tywrap__', 'codecVersion', 'encoding', 'value'}) + + +class PrototypeError(ValueError): + """A value cannot satisfy the proposed extension contract.""" + + +@dataclass +class Budget: + nodes: int = 0 + + def visit(self, path: str, depth: int) -> None: + self.nodes += 1 + if depth > MAX_DEPTH: + raise PrototypeError(f'maximum depth {MAX_DEPTH} exceeded at {path}') + if self.nodes > MAX_NODES: + raise PrototypeError(f'maximum nodes {MAX_NODES} exceeded at {path}') + + +def _check_payload(value: object, max_payload_bytes: int) -> None: + try: + encoded = json.dumps( + value, allow_nan=False, ensure_ascii=False, separators=(',', ':') + ) + byte_count = len(encoded.encode('utf-8')) + except (UnicodeEncodeError, ValueError) as exc: + raise PrototypeError('payload is not finite UTF-8 JSON') from exc + if byte_count > max_payload_bytes: + raise PrototypeError(f'payload exceeds {max_payload_bytes} bytes') + + +def _version_two(value: object) -> bool: + return type(value) in (int, float) and value == 2 + + +def _child(path: str, key: str | int) -> str: + return f'{path}[{key}]' if isinstance(key, int) else f'{path}.{key}' + + +def require_capability(meta: Mapping[str, object], feature: str, policy: str) -> None: + capabilities = meta.get('valueCapabilities') + if not isinstance(capabilities, list) or feature not in capabilities: + raise PrototypeError(f'bridge lacks {feature} capability') + expected_policy = { + 'exactIntegerDecimalV2': 'bigint-v2', + 'dataclassFieldsV2': 'fields-v2', + }.get(feature) + if policy != expected_policy: + raise PrototypeError(f'unsupported per-call value policy {policy!r}') + + +def _canonical_decimal(value: object, path: str) -> int: + if not isinstance(value, str) or not DECIMAL.fullmatch(value): + raise PrototypeError(f'noncanonical integer decimal at {path}') + digits = len(value) - (1 if value.startswith('-') else 0) + if digits > MAX_DECIMAL_DIGITS: + raise PrototypeError(f'integer exceeds {MAX_DECIMAL_DIGITS} digits at {path}') + return int(value) + + +def _integer_envelope(value: int, path: str) -> dict[str, object]: + if abs(value) >= MAX_INTEGER_MAGNITUDE: + raise PrototypeError(f'integer exceeds {MAX_DECIMAL_DIGITS} digits at {path}') + try: + decimal = str(value) + except ValueError as exc: + raise PrototypeError(f'integer conversion failed at {path}') from exc + _canonical_decimal(decimal, path) + return { + '__tywrap__': 'integer', + 'codecVersion': 2, + 'encoding': 'decimal', + 'value': decimal, + } + + +def encode_exact_integers( + value: object, + *, + max_payload_bytes: int = MAX_PAYLOAD_BYTES, +) -> object: + """Encode all Python integers as exact tagged values for an opted call.""" + budget = Budget() + active: set[int] = set() + + def visit(current: object, path: str, depth: int) -> object: + budget.visit(path, depth) + if current is None or type(current) in (bool, str): + return current + if type(current) is int: + return _integer_envelope(current, path) + if type(current) is float and math.isfinite(current): + return current + if isinstance(current, (list, tuple, dict)): + marker = id(current) + if marker in active: + raise PrototypeError(f'cycle at {path}') + active.add(marker) + try: + if isinstance(current, dict): + if any(not isinstance(key, str) for key in current): + raise PrototypeError(f'non-string record key at {path}') + if '__tywrap__' in current: + raise PrototypeError(f'reserved record key at {path}.__tywrap__') + return { + key: visit(item, _child(path, key), depth + 1) + for key, item in current.items() + } + return [ + visit(item, _child(path, index), depth + 1) + for index, item in enumerate(current) + ] + finally: + active.remove(marker) + raise PrototypeError(f'unsupported value at {path}: {type(current).__name__}') + + result = visit(value, 'result', 0) + _check_payload(result, max_payload_bytes) + return result + + +def decode_exact_integers( + value: object, + contract: Mapping[str, Any], + *, + max_payload_bytes: int = MAX_PAYLOAD_BYTES, +) -> object: + """Decode an opted request with its trusted resolved value contract.""" + _check_payload(value, max_payload_bytes) + budget = Budget() + active: set[int] = set() + + def visit( + current: object, spec: Mapping[str, Any], path: str, depth: int + ) -> object: + kind = spec.get('kind') + if kind == 'nullable': + if current is None: + return visit(None, {'kind': 'null'}, path, depth) + return visit(current, spec['value'], path, depth) + budget.visit(path, depth) + marker = id(current) if isinstance(current, (list, dict)) else None + if marker is not None: + if marker in active: + raise PrototypeError(f'cycle at {path}') + active.add(marker) + try: + if kind == 'null': + if current is not None: + raise PrototypeError(f'expected null at {path}') + return None + if kind == 'boolean': + if type(current) is not bool: + raise PrototypeError(f'expected boolean at {path}') + return current + if kind == 'string': + if type(current) is not str: + raise PrototypeError(f'expected string at {path}') + return current + if kind == 'integer': + if not isinstance(current, dict): + raise PrototypeError(f'untagged integer at {path}') + if ( + set(current) != INTEGER_FIELDS + or current.get('__tywrap__') != 'integer' + or not _version_two(current.get('codecVersion')) + or current.get('encoding') != 'decimal' + ): + raise PrototypeError(f'invalid integer envelope at {path}') + return _canonical_decimal(current['value'], _child(path, 'value')) + if kind == 'safe-integer': + if ( + type(current) is not int + or current < -SAFE_INTEGER_MAX + or current > SAFE_INTEGER_MAX + ): + raise PrototypeError(f'expected safe integer at {path}') + return current + if kind == 'float': + if isinstance(current, dict): + if current != { + '__tywrap__': 'float', + 'codecVersion': 2, + 'encoding': 'negative-zero', + } or not _version_two(current.get('codecVersion')): + raise PrototypeError(f'invalid float envelope at {path}') + return -0.0 + if type(current) not in (int, float): + raise PrototypeError(f'expected finite float at {path}') + try: + result = float(current) + except OverflowError as exc: + raise PrototypeError(f'expected finite float at {path}') from exc + if not math.isfinite(result): + raise PrototypeError(f'expected finite float at {path}') + return result + if kind == 'array': + if not isinstance(current, list): + raise PrototypeError(f'expected array at {path}') + return [ + visit(item, spec['item'], _child(path, index), depth + 1) + for index, item in enumerate(current) + ] + if kind == 'record': + if not isinstance(current, dict): + raise PrototypeError(f'expected record at {path}') + fields = spec['fields'] + if '__tywrap__' in current: + raise PrototypeError(f'reserved record key at {path}.__tywrap__') + if set(current) != set(fields): + raise PrototypeError(f'fields differ at {path}') + return { + key: visit(current[key], field, _child(path, key), depth + 1) + for key, field in fields.items() + } + raise PrototypeError(f'unsupported contract kind {kind!r} at {path}') + finally: + if marker is not None: + active.remove(marker) + + return visit(value, contract, 'args', 0) + + +def encode_dataclass( + value: object, + expected_type: type, + *, + max_payload_bytes: int = MAX_PAYLOAD_BYTES, +) -> dict[str, object]: + """Encode only an annotated dataclass result as a version 2 envelope.""" + if type(value) is not expected_type or not dataclasses.is_dataclass(value): + raise PrototypeError('result is not the declared dataclass type') + budget = Budget() + active: set[int] = set() + + def visit(current: object, path: str, depth: int) -> object: + budget.visit(path, depth) + if current is None or type(current) in (bool, str): + return current + if type(current) is int: + if current < -SAFE_INTEGER_MAX or current > SAFE_INTEGER_MAX: + raise PrototypeError(f'unsafe integer at {path}') + return current + if type(current) is float and math.isfinite(current): + return current + if dataclasses.is_dataclass(current) and not isinstance(current, type): + marker = id(current) + if marker in active: + raise PrototypeError(f'cycle at {path}') + active.add(marker) + try: + cls = type(current) + fields = { + field.name: visit( + getattr(current, field.name), + _child(path, field.name), + depth + 1, + ) + for field in dataclasses.fields(current) + } + return { + '__tywrap__': 'dataclass', + 'codecVersion': 2, + 'encoding': 'fields', + 'type': f'{cls.__module__}.{cls.__qualname__}', + 'fields': fields, + } + finally: + active.remove(marker) + if isinstance(current, (list, tuple, dict)): + marker = id(current) + if marker in active: + raise PrototypeError(f'cycle at {path}') + active.add(marker) + try: + if isinstance(current, dict): + if any(not isinstance(key, str) for key in current): + raise PrototypeError(f'non-string record key at {path}') + if '__tywrap__' in current: + raise PrototypeError(f'reserved record key at {path}.__tywrap__') + return { + key: visit(item, _child(path, key), depth + 1) + for key, item in current.items() + } + return [ + visit(item, _child(path, index), depth + 1) + for index, item in enumerate(current) + ] + finally: + active.remove(marker) + raise PrototypeError(f'unsupported value at {path}: {type(current).__name__}') + + result = visit(value, 'result', 0) + assert isinstance(result, dict) + _check_payload(result, max_payload_bytes) + return result + + +@dataclass +class Point: + x: int + y: int + + +INTEGER_TEST_CONTRACT: dict[str, Any] = { + 'kind': 'record', + 'fields': { + 'positive': {'kind': 'array', 'item': {'kind': 'integer'}}, + 'negative': { + 'kind': 'record', + 'fields': {'value': {'kind': 'integer'}}, + }, + 'safe': {'kind': 'integer'}, + 'flag': {'kind': 'boolean'}, + 'whole': {'kind': 'float'}, + 'fraction': {'kind': 'float'}, + 'negativeZero': {'kind': 'float'}, + 'mixed': { + 'kind': 'array', + 'item': { + 'kind': 'record', + 'fields': { + 'quantity': {'kind': 'integer'}, + 'ratio': {'kind': 'float'}, + 'flag': {'kind': 'boolean'}, + }, + }, + }, + }, +} + + +def _main() -> None: + raw = sys.stdin.buffer.read(MAX_PAYLOAD_BYTES + 1) + if len(raw) > MAX_PAYLOAD_BYTES: + raise PrototypeError('input payload exceeds byte limit') + payload: Any = json.loads(raw) + action = sys.argv[1] + if action == 'roundtrip-integer': + require_capability( + payload['meta'], 'exactIntegerDecimalV2', payload['policy'] + ) + result = encode_exact_integers( + decode_exact_integers(payload['value'], INTEGER_TEST_CONTRACT) + ) + elif action == 'encode-integer': + result = encode_exact_integers(payload) + elif action == 'encode-integer-limited': + result = encode_exact_integers( + payload['value'], max_payload_bytes=payload['limit'] + ) + elif action == 'roundtrip-single-integer': + require_capability( + payload['meta'], 'exactIntegerDecimalV2', payload['policy'] + ) + result = encode_exact_integers( + decode_exact_integers(payload['value'], {'kind': 'integer'}) + ) + elif action == 'encode-point': + result = encode_dataclass(Point(**payload), Point) + else: + raise PrototypeError(f'unknown action {action!r}') + wire = json.dumps( + result, allow_nan=False, ensure_ascii=False, separators=(',', ':') + ).encode('utf-8') + sys.stdout.buffer.write(wire + b'\n') + + +if __name__ == '__main__': + _main() diff --git a/test/prototypes/value_extensions.ts b/test/prototypes/value_extensions.ts new file mode 100644 index 00000000..67d8d4f4 --- /dev/null +++ b/test/prototypes/value_extensions.ts @@ -0,0 +1,276 @@ +/** Isolated value extension prototype. Shipped codecs never import this file. */ + +export type PrototypeContract = + | { readonly kind: 'integer' } + | { readonly kind: 'safe-integer' } + | { readonly kind: 'float' } + | { readonly kind: 'boolean' } + | { readonly kind: 'string' } + | { readonly kind: 'null' } + | { readonly kind: 'nullable'; readonly value: PrototypeContract } + | { readonly kind: 'array'; readonly item: PrototypeContract } + | { readonly kind: 'record'; readonly fields: Readonly> } + | { + readonly kind: 'dataclass'; + readonly typeId: string; + readonly fields: Readonly>; + }; + +const MAX_DECIMAL_DIGITS = 4096; +const MAX_DEPTH = 64; +const MAX_NODES = 100_000; +const MAX_PAYLOAD_BYTES = 10 * 1024 * 1024; +const DECIMAL = /^(?:0|[1-9][0-9]*|-[1-9][0-9]*)$/; +const provenance = new WeakMap(); + +export class PrototypeError extends Error {} + +function isRecord(value: unknown): value is Record { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +function exactKeys( + value: Record, + expected: readonly string[], + path: string +): void { + const actual = Object.keys(value).sort(); + const required = [...expected].sort(); + if (actual.length !== required.length || actual.some((key, index) => key !== required[index])) { + throw new PrototypeError(`fields differ at ${path}`); + } +} + +function checkPayload(value: unknown, limit: number): void { + const assertUnicodeScalars = (text: string): void => { + for (let index = 0; index < text.length; index += 1) { + const code = text.charCodeAt(index); + if (code >= 0xd800 && code <= 0xdbff) { + const next = text.charCodeAt(index + 1); + if (!(next >= 0xdc00 && next <= 0xdfff)) { + throw new PrototypeError('payload contains an unpaired Unicode surrogate'); + } + index += 1; + } else if (code >= 0xdc00 && code <= 0xdfff) { + throw new PrototypeError('payload contains an unpaired Unicode surrogate'); + } + } + }; + const encoded = JSON.stringify(value, (key, item: unknown) => { + assertUnicodeScalars(key); + if (typeof item === 'string') assertUnicodeScalars(item); + return item; + }); + if (encoded === undefined || new TextEncoder().encode(encoded).length > limit) { + throw new PrototypeError(`payload exceeds ${limit} bytes`); + } +} + +function canonicalDecimal(value: unknown, path: string): bigint { + if (typeof value !== 'string' || !DECIMAL.test(value)) { + throw new PrototypeError(`noncanonical integer decimal at ${path}`); + } + const digits = value.startsWith('-') ? value.length - 1 : value.length; + if (digits > MAX_DECIMAL_DIGITS) { + throw new PrototypeError(`integer exceeds ${MAX_DECIMAL_DIGITS} digits at ${path}`); + } + return BigInt(value); +} + +export function requireCapability(meta: unknown, feature: string, policy: string): void { + const capabilities = isRecord(meta) ? meta.valueCapabilities : undefined; + if (!Array.isArray(capabilities) || !capabilities.includes(feature)) { + throw new PrototypeError(`bridge lacks ${feature} capability`); + } + const expected = + feature === 'exactIntegerDecimalV2' + ? 'bigint-v2' + : feature === 'dataclassFieldsV2' + ? 'fields-v2' + : undefined; + if (policy !== expected) { + throw new PrototypeError(`unsupported per-call value policy ${policy}`); + } +} + +interface WalkState { + nodes: number; + active: WeakSet; +} + +function visit(state: WalkState, value: unknown, path: string, depth: number): void { + state.nodes += 1; + if (depth > MAX_DEPTH) { + throw new PrototypeError(`maximum depth ${MAX_DEPTH} exceeded at ${path}`); + } + if (state.nodes > MAX_NODES) { + throw new PrototypeError(`maximum nodes ${MAX_NODES} exceeded at ${path}`); + } + if (typeof value === 'object' && value !== null) { + if (state.active.has(value)) { + throw new PrototypeError(`cycle at ${path}`); + } + state.active.add(value); + } +} + +function leave(state: WalkState, value: unknown): void { + if (typeof value === 'object' && value !== null) { + state.active.delete(value); + } +} + +function walk( + value: unknown, + contract: PrototypeContract, + mode: 'encode' | 'decode', + path: string, + depth: number, + state: WalkState +): unknown { + if (contract.kind === 'nullable') { + return value === null + ? walk(null, { kind: 'null' }, mode, path, depth, state) + : walk(value, contract.value, mode, path, depth, state); + } + visit(state, value, path, depth); + try { + if (contract.kind === 'null') { + if (value !== null) throw new PrototypeError(`expected null at ${path}`); + return null; + } + if (contract.kind === 'boolean' || contract.kind === 'string') { + if (typeof value !== contract.kind) { + throw new PrototypeError(`expected ${contract.kind} at ${path}`); + } + return value; + } + if (contract.kind === 'float') { + if (mode === 'decode' && isRecord(value)) { + exactKeys(value, ['__tywrap__', 'codecVersion', 'encoding'], path); + if ( + value.__tywrap__ !== 'float' || + value.codecVersion !== 2 || + value.encoding !== 'negative-zero' + ) { + throw new PrototypeError(`invalid float envelope at ${path}`); + } + return -0; + } + if (typeof value !== 'number' || !Number.isFinite(value)) { + throw new PrototypeError(`expected finite float at ${path}`); + } + if (mode === 'encode' && Object.is(value, -0)) { + return { __tywrap__: 'float', codecVersion: 2, encoding: 'negative-zero' }; + } + return value; + } + if (contract.kind === 'safe-integer') { + if (typeof value !== 'number' || !Number.isSafeInteger(value)) { + throw new PrototypeError(`expected safe integer at ${path}`); + } + return value; + } + if (contract.kind === 'integer') { + if (mode === 'encode') { + if (typeof value !== 'bigint') { + throw new PrototypeError(`expected bigint at ${path}`); + } + const decimal = value.toString(); + canonicalDecimal(decimal, path); + return { __tywrap__: 'integer', codecVersion: 2, encoding: 'decimal', value: decimal }; + } + if (!isRecord(value)) { + throw new PrototypeError(`expected integer envelope at ${path}`); + } + exactKeys(value, ['__tywrap__', 'codecVersion', 'encoding', 'value'], path); + if ( + value.__tywrap__ !== 'integer' || + value.codecVersion !== 2 || + value.encoding !== 'decimal' + ) { + throw new PrototypeError(`invalid integer envelope at ${path}`); + } + return canonicalDecimal(value.value, `${path}.value`); + } + if (contract.kind === 'array') { + if (!Array.isArray(value)) throw new PrototypeError(`expected array at ${path}`); + return value.map((item, index) => + walk(item, contract.item, mode, `${path}[${index}]`, depth + 1, state) + ); + } + if (contract.kind === 'record') { + if (!isRecord(value)) throw new PrototypeError(`expected record at ${path}`); + if (Object.hasOwn(value, '__tywrap__')) { + throw new PrototypeError(`reserved record key at ${path}.__tywrap__`); + } + exactKeys(value, Object.keys(contract.fields), path); + return Object.fromEntries( + Object.entries(contract.fields).map(([key, field]) => [ + key, + walk(value[key], field, mode, `${path}.${key}`, depth + 1, state), + ]) + ); + } + if (mode === 'encode') { + throw new PrototypeError(`dataclass inputs are unsupported at ${path}`); + } + if (!isRecord(value)) throw new PrototypeError(`expected dataclass envelope at ${path}`); + exactKeys(value, ['__tywrap__', 'codecVersion', 'encoding', 'type', 'fields'], path); + if ( + value.__tywrap__ !== 'dataclass' || + value.codecVersion !== 2 || + value.encoding !== 'fields' || + value.type !== contract.typeId || + !isRecord(value.fields) + ) { + throw new PrototypeError(`invalid dataclass identity at ${path}`); + } + exactKeys(value.fields, Object.keys(contract.fields), `${path}.fields`); + const decoded = Object.fromEntries( + Object.entries(contract.fields).map(([key, field]) => [ + key, + walk(value.fields[key], field, 'decode', `${path}.fields.${key}`, depth + 1, state), + ]) + ); + provenance.set(decoded, contract); + return decoded; + } finally { + leave(state, value); + } +} + +export function encodeExactRequest( + value: unknown, + contract: PrototypeContract, + maxPayloadBytes = MAX_PAYLOAD_BYTES +): unknown { + const encoded = walk(value, contract, 'encode', 'args', 0, { + nodes: 0, + active: new WeakSet(), + }); + checkPayload(encoded, maxPayloadBytes); + return encoded; +} + +export function decodeExactResponse( + value: unknown, + contract: PrototypeContract, + maxPayloadBytes = MAX_PAYLOAD_BYTES +): unknown { + checkPayload(value, maxPayloadBytes); + return walk(value, contract, 'decode', 'result', 0, { + nodes: 0, + active: new WeakSet(), + }); +} + +export function validateDataclassOrigin(value: unknown, contract: PrototypeContract): void { + if (contract.kind !== 'dataclass' || !isRecord(value) || provenance.get(value) !== contract) { + throw new PrototypeError('value lacks verified dataclass provenance'); + } +} diff --git a/test/python/architecture_numeric_oracle.py b/test/python/architecture_numeric_oracle.py new file mode 100644 index 00000000..d33ff21b --- /dev/null +++ b/test/python/architecture_numeric_oracle.py @@ -0,0 +1,56 @@ +"""Produce independent binary16 and safe-integer expectations for conformance tests.""" + +from __future__ import annotations + +import json +import math +import struct +import sys +from pathlib import Path + + +CONTRACT_REVISION = 2 +SAFE_INTEGER_MAX = (1 << 53) - 1 + + +def binary16_word(word: int) -> tuple[str, bool]: + """Read one raw binary16 word with Python's standard IEEE 754 decoder.""" + value = struct.unpack('>e', word.to_bytes(2, 'big'))[0] + if math.isnan(value): + return 'NaN', False + if math.isinf(value): + return ('-Infinity' if value < 0 else '+Infinity'), False + negative_zero = value == 0.0 and math.copysign(1.0, value) < 0 + return repr(value), negative_zero + + +def main() -> None: + if len(sys.argv) != 2: + raise SystemExit('usage: architecture_numeric_oracle.py FIXTURE_JSON') + + fixture = json.loads(Path(sys.argv[1]).read_text(encoding='utf8')) + if fixture['schemaVersion'] != 1 or fixture['contractRevision'] != CONTRACT_REVISION: + raise ValueError('architecture fixture version does not match the oracle') + + integers = [] + for case in fixture['safeIntegers']: + value = int(case['decimal']) + integers.append( + {'decimal': case['decimal'], 'accepted': -SAFE_INTEGER_MAX <= value <= SAFE_INTEGER_MAX} + ) + + json.dump( + { + 'contractRevision': CONTRACT_REVISION, + 'method': 'python-stdlib-struct-unpack-binary16', + 'words': [binary16_word(word) for word in range(1 << 16)], + 'integers': integers, + }, + sys.stdout, + separators=(',', ':'), + allow_nan=False, + ) + + +if __name__ == '__main__': + main() diff --git a/test/python/test_bridge_core.py b/test/python/test_bridge_core.py index 38d5c164..e60b4594 100644 --- a/test/python/test_bridge_core.py +++ b/test/python/test_bridge_core.py @@ -6,12 +6,15 @@ import subprocess import sys import tracemalloc +import types from pathlib import Path import pytest RUNTIME_DIR = Path(__file__).parent.parent.parent / 'runtime' +VALUE_CONTRACT_PATH = RUNTIME_DIR.parent / 'docs' / 'maintainers' / 'value-contracts.v2.json' +VALUE_FIXTURES_PATH = RUNTIME_DIR.parent / 'docs' / 'maintainers' / 'value-contract-fixtures.v2.json' sys.path.insert(0, str(RUNTIME_DIR)) @@ -28,10 +31,264 @@ serialize, serialize_dataframe_json, serialize_ndarray_json, + serialize_series, serialize_series_json, + serialize_sparse_matrix, ) +def test_safe_integer_policy_matches_frozen_specification() -> None: + specification = json.loads(VALUE_CONTRACT_PATH.read_text()) + assert specification['revision'] == 2 + assert specification['codecVersion'] == bridge_core.CODEC_VERSION + assert specification['rules']['integer']['maximum'] == bridge_core.JS_SAFE_INTEGER_MAX + assert specification['rules']['integer']['minimum'] == -bridge_core.JS_SAFE_INTEGER_MAX + + +def test_fixed_integer_proof_fixtures() -> None: + fixtures = json.loads(VALUE_FIXTURES_PATH.read_text()) + assert fixtures['revision'] == 2 + for case in fixtures['integerCases']: + value = int(case['decimal']) + if case['outcome'] == 'reject': + with pytest.raises(RuntimeError, match='Unsafe Python integer at result:'): + serialize(value, force_json_markers=True) + else: + assert serialize(value, force_json_markers=True) == value + + +@pytest.mark.parametrize('value', [2**53, -(2**53), 2**63 - 1, -(2**63)]) +def test_unsafe_integer_rejection_names_root_and_nested_paths(value: int) -> None: + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result:.*return an explicit string'): + serialize(value, force_json_markers=True) + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result\.items\[0\]:'): + serialize({'items': [value]}, force_json_markers=True) + + +def test_safe_integer_edges_and_finite_floats_still_encode() -> None: + value = [-(2**53 - 1), 2**53 - 1, True, False, -0.0, 1.5] + serialized = serialize(value, force_json_markers=True) + assert json.loads(encode_value(serialized, allow_nan=False)) == value + + +def test_model_dump_values_follow_nested_integer_policy() -> None: + class Model: + def model_dump(self, **_kwargs: object) -> dict[str, object]: + return {'nested': {'value': 2**53 + 1}} + + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result\.nested\.value:'): + serialize(Model(), force_json_markers=True) + + class ScalarModel: + def model_dump(self, **_kwargs: object) -> int: + return 2**53 + + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result:'): + serialize(ScalarModel(), force_json_markers=True) + + +def test_mapping_model_dump_keeps_alias_precedence() -> None: + class ModelMap(dict[str, int]): + def model_dump(self, **_kwargs: object) -> dict[str, int]: + return {'from_alias': self['internal']} + + value = ModelMap(internal=7) + assert serialize(value, force_json_markers=True) == {'from_alias': 7} + assert serialize({'item': value}, force_json_markers=True) == { + 'item': {'from_alias': 7} + } + + +def test_model_dump_cycle_rejects_without_recursing_forever() -> None: + class Model: + other: object + + def model_dump(self, **_kwargs: object) -> object: + return self.other + + first = Model() + second = Model() + first.other = second + second.other = first + + with pytest.raises(RuntimeError, match='Circular model conversion detected at result'): + serialize(first, force_json_markers=True) + + +def test_long_model_dump_chain_obeys_depth_and_node_limits( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class Model: + def __init__(self, other: object): + self.other = other + + def model_dump(self, **_kwargs: object) -> object: + return self.other + + value: object = 1 + for _ in range(10): + value = Model(value) + + monkeypatch.setattr(bridge_core, 'MAX_SERIALIZE_DEPTH', 4) + with pytest.raises(RuntimeError, match='maximum depth 4 exceeded at result'): + serialize(value, force_json_markers=True) + + monkeypatch.setattr(bridge_core, 'MAX_SERIALIZE_DEPTH', MAX_SERIALIZE_DEPTH) + monkeypatch.setattr(bridge_core, 'MAX_SERIALIZE_NODES', 4) + with pytest.raises(RuntimeError, match='maximum visited nodes 4 exceeded at result'): + serialize(value, force_json_markers=True) + + +def test_nested_pydantic_models_keep_value_semantics() -> None: + pydantic = pytest.importorskip('pydantic') + if not hasattr(pydantic.BaseModel, 'model_dump'): + pytest.skip('Pydantic v2 is required') + + class Child(pydantic.BaseModel): + count: int + + class Parent(pydantic.BaseModel): + child: Child + items: list[int] + + value = Parent(child=Child(count=3), items=[4, 5]) + assert serialize(value, force_json_markers=True) == { + 'child': {'count': 3}, + 'items': [4, 5], + } + + +def test_numpy_scalar_follows_nested_integer_policy() -> None: + np = pytest.importorskip('numpy') + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result\.nested\[0\]:'): + serialize({'nested': [np.int64(2**53)]}, force_json_markers=True) + + +def test_integer_subclass_cannot_bypass_policy() -> None: + class IntegerSubclass(int): + pass + + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result\.value:'): + serialize({'value': IntegerSubclass(2**53)}, force_json_markers=True) + + class RecordSubclass(dict[str, int]): + pass + + class ListSubclass(list[int]): + pass + + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result\.value:'): + serialize(RecordSubclass(value=2**53), force_json_markers=True) + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result\[0\]:'): + serialize(ListSubclass([2**53]), force_json_markers=True) + + class MisleadingInteger(int): + def __lt__(self, _other: object) -> bool: + return False + + def __gt__(self, _other: object) -> bool: + return False + + def __int__(self) -> int: + return 0 + + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result\.value:'): + serialize({'value': MisleadingInteger(2**53 + 1)}, force_json_markers=True) + + +@pytest.mark.parametrize('container_type', [set, frozenset]) +def test_set_subclass_values_follow_nested_integer_policy(container_type: type) -> None: + class SetSubclass(container_type): + pass + + for force_json_markers in (False, True): + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result\.items\[0\]:'): + serialize({'items': SetSubclass([2**53 + 1])}, force_json_markers=force_json_markers) + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result\[0\]:'): + serialize(SetSubclass([2**53 + 1]), force_json_markers=force_json_markers) + + safe = serialize({'items': SetSubclass([2**53 - 1])}, force_json_markers=force_json_markers) + assert json.loads(encode_value(safe, allow_nan=False)) == { + 'items': [2**53 - 1] + } + + +def test_estimator_metadata_rejects_nested_unsafe_integer( + monkeypatch: pytest.MonkeyPatch, +) -> None: + sklearn = types.ModuleType('sklearn') + sklearn.__version__ = 'stub' + sklearn_base = types.ModuleType('sklearn.base') + + class BaseEstimator: + pass + + sklearn_base.BaseEstimator = BaseEstimator + sklearn.base = sklearn_base + monkeypatch.setitem(sys.modules, 'sklearn', sklearn) + monkeypatch.setitem(sys.modules, 'sklearn.base', sklearn_base) + + class Estimator(BaseEstimator): + def __init__(self, value: int): + self.value = value + + def get_params(self, *, deep: bool) -> dict[str, object]: + assert deep is False + return {'config': {'nested': {'unsafe': self.value}}} + + for force_json_markers in (False, True): + with pytest.raises( + RuntimeError, + match=r'Unsafe Python integer at result\.params\.config\.nested\.unsafe:', + ): + serialize(Estimator(2**53 + 1), force_json_markers=force_json_markers) + + with pytest.raises( + RuntimeError, + match=r'Unsafe Python integer at result\.fit\.params\.config\.nested\.unsafe:', + ): + serialize({'fit': Estimator(2**53)}, force_json_markers=True) + + safe = serialize(Estimator(2**53 - 1), force_json_markers=True) + assert json.loads(encode_value(safe, allow_nan=False))['params']['config']['nested'][ + 'unsafe' + ] == 2**53 - 1 + + +def test_terminal_scientific_metadata_rejects_unsafe_integer() -> None: + class Series: + name = 2**53 + + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result\.name:'): + serialize_series(Series(), force_json_markers=False) + + class EmptyData: + size = 0 + + class Sparse: + dtype = types.SimpleNamespace(kind='i') + data = EmptyData() + shape = (2**53, 1) + + def getformat(self) -> str: + return 'coo' + + with pytest.raises(RuntimeError, match=r'Unsafe Python integer at result\.shape\[0\]:'): + serialize_sparse_matrix(Sparse()) + + +def test_json_scientific_values_report_unsafe_integer_path() -> None: + np = pytest.importorskip('numpy') + sparse = pytest.importorskip('scipy.sparse') + with pytest.raises(RuntimeError, match=r'failed at result:.*safe integer range'): + serialize(np.array([2**53], dtype=np.int64), force_json_markers=True) + with pytest.raises(RuntimeError, match=r'failed at result\.matrix:.*safe integer range'): + serialize( + {'matrix': sparse.csr_matrix([[2**53]])}, + force_json_markers=True, + ) + + def test_plain_values_do_not_import_scientific_codecs() -> None: """Plain JSON values must not cold-import optional scientific packages.""" script = f""" diff --git a/test/python/test_frame_codec.py b/test/python/test_frame_codec.py index 13a95729..e63f29ef 100644 --- a/test/python/test_frame_codec.py +++ b/test/python/test_frame_codec.py @@ -139,6 +139,21 @@ def test_many_frames(self) -> None: assert {f['totalBytes'] for f in frames} == {utf8_byte_length(logical)} assert round_trip(logical, 256) == logical + def test_ascii_exact_and_partial_frame_boundaries(self) -> None: + logical = 'x' * 2049 + frames = encode_frames(logical, id=1, stream='response', max_frame_bytes=1024) + assert [len(frame['data']) for frame in frames] == [1024, 1024, 1] + assert [frame['seq'] for frame in frames] == [0, 1, 2] + assert {frame['totalBytes'] for frame in frames} == {2049} + assert round_trip(logical, 1024) == logical + + def test_non_ascii_near_frame_boundary(self) -> None: + logical = 'x' * 1023 + 'é' + 'y' + frames = encode_frames(logical, id=1, stream='response', max_frame_bytes=1024) + assert [frame['data'] for frame in frames] == ['x' * 1023, 'éy'] + assert [utf8_byte_length(frame['data']) for frame in frames] == [1023, 3] + assert round_trip(logical, 1024) == logical + def test_empty_payload_one_empty_frame(self) -> None: frames = encode_frames('', id=1, stream='response', max_frame_bytes=64) assert len(frames) == 1 diff --git a/test/python/test_value_extensions_prototype.py b/test/python/test_value_extensions_prototype.py new file mode 100644 index 00000000..0ae5fef4 --- /dev/null +++ b/test/python/test_value_extensions_prototype.py @@ -0,0 +1,264 @@ +"""Bounded design tests. These codecs are not part of the shipped bridge.""" + +from __future__ import annotations + +import math +import json +import sys +from dataclasses import dataclass, field +from pathlib import Path + +import pytest + + +sys.path.insert(0, str(Path(__file__).parent.parent / 'prototypes')) +import value_extensions as prototype # noqa: E402 + +INTEGER = {'kind': 'integer'} + + +def test_nested_exact_integers_round_trip_beyond_int64() -> None: + value = { + 'outer': [2**80 + 1, -(2**130 + 7)], + 'nested': {'negative': -(2**130 + 7)}, + 'safe': 7, + 'flag': True, + } + encoded = prototype.encode_exact_integers(value) + assert encoded['outer'][0]['value'] == str(2**80 + 1) + assert encoded['safe']['value'] == '7' + assert encoded['flag'] is True + contract = { + 'kind': 'record', + 'fields': { + 'outer': {'kind': 'array', 'item': INTEGER}, + 'nested': {'kind': 'record', 'fields': {'negative': INTEGER}}, + 'safe': INTEGER, + 'flag': {'kind': 'boolean'}, + }, + } + assert prototype.decode_exact_integers(encoded, contract) == value + + +@pytest.mark.parametrize('bad', ['-0', '+1', '01', '-01', '1.0', '1e2', ' 1', '١']) +def test_integer_decimal_rejects_noncanonical_values(bad: str) -> None: + envelope = { + '__tywrap__': 'integer', + 'codecVersion': 2, + 'encoding': 'decimal', + 'value': bad, + } + with pytest.raises(prototype.PrototypeError, match='noncanonical integer decimal'): + prototype.decode_exact_integers( + {'item': [envelope]}, + { + 'kind': 'record', + 'fields': {'item': {'kind': 'array', 'item': INTEGER}}, + }, + ) + + +def test_integer_digit_and_payload_caps() -> None: + accepted = int('9' * prototype.MAX_DECIMAL_DIGITS) + assert prototype.decode_exact_integers( + prototype.encode_exact_integers(accepted), INTEGER + ) == accepted + with pytest.raises(prototype.PrototypeError, match='4096 digits'): + prototype.encode_exact_integers(int('9' * (prototype.MAX_DECIMAL_DIGITS + 1))) + with pytest.raises( + prototype.PrototypeError, match=r'4096 digits at result.big\[0\]' + ): + prototype.encode_exact_integers({'big': [10**5000]}) + with pytest.raises(prototype.PrototypeError, match='payload exceeds 80 bytes'): + prototype.encode_exact_integers({'text': 'x' * 80}, max_payload_bytes=80) + + +def test_unicode_payload_cap_counts_compact_utf8_bytes() -> None: + assert prototype.encode_exact_integers('é', max_payload_bytes=4) == 'é' + with pytest.raises(prototype.PrototypeError, match='payload exceeds 3 bytes'): + prototype.encode_exact_integers('é', max_payload_bytes=3) + + nested = {'café': ['🍵', 'é']} + expected_bytes = len('{"café":["🍵","é"]}'.encode('utf-8')) + assert prototype.encode_exact_integers( + nested, max_payload_bytes=expected_bytes + ) == nested + with pytest.raises(prototype.PrototypeError, match='payload exceeds'): + prototype.encode_exact_integers( + nested, max_payload_bytes=expected_bytes - 1 + ) + + +@pytest.mark.parametrize( + ('version_token', 'accepted'), + [('2', True), ('2.0', True), ('2e0', True), ('true', False), ('"2"', False), ('2.5', False), ('null', False)], +) +def test_integer_version_uses_json_numeric_value(version_token: str, accepted: bool) -> None: + envelope = json.loads( + '{"__tywrap__":"integer","codecVersion":' + + version_token + + ',"encoding":"decimal","value":"7"}' + ) + if accepted: + assert prototype.decode_exact_integers(envelope, INTEGER) == 7 + else: + with pytest.raises(prototype.PrototypeError): + prototype.decode_exact_integers(envelope, INTEGER) + + +def test_integer_envelope_and_capability_fail_closed() -> None: + encoded = prototype.encode_exact_integers(2**80) + for change in ( + {'codecVersion': 1}, + {'encoding': 'json'}, + {'unexpected': True}, + ): + with pytest.raises(prototype.PrototypeError, match='invalid integer envelope'): + prototype.decode_exact_integers({**encoded, **change}, INTEGER) + with pytest.raises(prototype.PrototypeError, match='untagged integer at args'): + prototype.decode_exact_integers(42, INTEGER) + with pytest.raises(prototype.PrototypeError, match='reserved record key at result.__tywrap__'): + prototype.encode_exact_integers({'__tywrap__': 'ordinary'}) + with pytest.raises(prototype.PrototypeError, match='bridge lacks'): + prototype.require_capability({}, 'exactIntegerDecimalV2', 'bigint-v2') + with pytest.raises(prototype.PrototypeError, match='unsupported per-call'): + prototype.require_capability( + {'valueCapabilities': ['exactIntegerDecimalV2']}, + 'exactIntegerDecimalV2', + 'fields-v2', + ) + + +def test_float_contract_recovers_integer_json_tokens_without_weakening_integer() -> None: + assert prototype.decode_exact_integers(1, {'kind': 'float'}) == 1.0 + assert type(prototype.decode_exact_integers(1, {'kind': 'float'})) is float + assert prototype.decode_exact_integers(1.5, {'kind': 'float'}) == 1.5 + zero = prototype.decode_exact_integers( + {'__tywrap__': 'float', 'codecVersion': 2, 'encoding': 'negative-zero'}, + {'kind': 'float'}, + ) + assert math.copysign(1, zero) == -1 + with pytest.raises(prototype.PrototypeError, match='untagged integer'): + prototype.decode_exact_integers(1, INTEGER) + with pytest.raises( + prototype.PrototypeError, + match=r'untagged integer at args\.mixed\[0\]\.quantity', + ): + prototype.decode_exact_integers( + {'mixed': [{'quantity': 1, 'ratio': 2, 'flag': True}]}, + { + 'kind': 'record', + 'fields': { + 'mixed': { + 'kind': 'array', + 'item': { + 'kind': 'record', + 'fields': { + 'quantity': INTEGER, + 'ratio': {'kind': 'float'}, + 'flag': {'kind': 'boolean'}, + }, + }, + }, + }, + }, + ) + with pytest.raises(prototype.PrototypeError, match='expected finite float'): + prototype.decode_exact_integers(True, {'kind': 'float'}) + with pytest.raises(prototype.PrototypeError, match='invalid float envelope'): + prototype.decode_exact_integers( + {'__tywrap__': 'float', 'codecVersion': 1, 'encoding': 'negative-zero'}, + {'kind': 'float'}, + ) + + +def test_integer_cycles_and_depth_reject_with_path() -> None: + cycle: list[object] = [] + cycle.append(cycle) + with pytest.raises(prototype.PrototypeError, match=r'cycle at result\[0\]'): + prototype.encode_exact_integers(cycle) + nested: object = 1 + for _ in range(prototype.MAX_DEPTH + 1): + nested = [nested] + with pytest.raises(prototype.PrototypeError, match='maximum depth'): + prototype.encode_exact_integers(nested) + + +def test_dataclass_point_fields_and_identity() -> None: + encoded = prototype.encode_dataclass(prototype.Point(1, 2), prototype.Point) + assert encoded == { + '__tywrap__': 'dataclass', + 'codecVersion': 2, + 'encoding': 'fields', + 'type': 'value_extensions.Point', + 'fields': {'x': 1, 'y': 2}, + } + + @dataclass + class Record: + name: str + optional: int | None = None + output: int = field(init=False, default=3) + + record = prototype.encode_dataclass(Record('a'), Record) + assert record['fields'] == {'name': 'a', 'optional': None, 'output': 3} + + +def test_dataclass_nested_values_and_failures() -> None: + @dataclass + class Container: + points: list[prototype.Point] + + encoded = prototype.encode_dataclass(Container([prototype.Point(1, 2)]), Container) + assert encoded['fields']['points'][0]['fields'] == {'x': 1, 'y': 2} + + with pytest.raises(prototype.PrototypeError, match='declared dataclass type'): + prototype.encode_dataclass(prototype.Point(1, 2), Container) + + class OrdinaryPoint: + def __init__(self, x: int, y: int) -> None: + self.x = x + self.y = y + + with pytest.raises(prototype.PrototypeError, match='declared dataclass type'): + prototype.encode_dataclass(OrdinaryPoint(1, 2), prototype.Point) + + @dataclass + class UnsupportedAnnotation: + x: object + y: int + + assert prototype.encode_dataclass( + UnsupportedAnnotation(1, 2), UnsupportedAnnotation + )['fields'] == {'x': 1, 'y': 2} + + @dataclass + class Unsupported: + value: object + + with pytest.raises(prototype.PrototypeError, match='unsupported value at result.value'): + prototype.encode_dataclass(Unsupported(object()), Unsupported) + + @dataclass + class Cyclic: + value: object = None + + cyclic = Cyclic() + cyclic.value = cyclic + with pytest.raises(prototype.PrototypeError, match='cycle at result.value'): + prototype.encode_dataclass(cyclic, Cyclic) + + with pytest.raises(prototype.PrototypeError, match='payload exceeds 60 bytes'): + prototype.encode_dataclass( + prototype.Point(1, 2), prototype.Point, max_payload_bytes=60 + ) + + @dataclass + class Nested: + value: object + + deep: object = 1 + for _ in range(prototype.MAX_DEPTH + 1): + deep = Nested(deep) + with pytest.raises(prototype.PrototypeError, match='maximum depth'): + prototype.encode_dataclass(deep, Nested) diff --git a/test/rpc-client.test.ts b/test/rpc-client.test.ts index b9aaa1eb..1bbc4255 100644 --- a/test/rpc-client.test.ts +++ b/test/rpc-client.test.ts @@ -503,6 +503,71 @@ describe('BridgeProtocol', () => { const parsed = JSON.parse(transport.lastMessage!); expect(parsed.params.kwargs).toEqual({ key: 'value' }); }); + + it('keeps equal scalar proof with each concurrent call', async () => { + transport.send = async message => { + const request = JSON.parse(message); + const dtype = request.params.functionName === 'half' ? 'float16' : 'float32'; + await new Promise(resolve => setTimeout(resolve, dtype === 'float16' ? 5 : 0)); + return JSON.stringify({ + id: request.id, + protocol: 'tywrap/1', + result: { + __tywrap__: 'ndarray', + codecVersion: 1, + encoding: 'json', + data: 1.5, + shape: [], + dtype, + }, + }); + }; + + const seen: string[] = []; + const [half, full] = await Promise.all([ + protocol.call('module', 'half', [], undefined, (value, provenance) => { + expect(value).toBe(1.5); + expect(provenance?.atRoot()?.dtype).toBe('float16'); + seen.push('half'); + }), + protocol.call('module', 'full', [], undefined, (value, provenance) => { + expect(value).toBe(1.5); + expect(provenance?.atRoot()?.dtype).toBe('float32'); + seen.push('full'); + }), + ]); + expect([half, full]).toEqual([1.5, 1.5]); + expect(seen).toHaveLength(2); + }); + + it('does not pass rejected decode proof to validation or a later call', async () => { + let bad = true; + transport.setDynamicResponse(() => + bad + ? { + __tywrap__: 'ndarray', + codecVersion: 1, + encoding: 'json', + data: 1.5, + shape: [1], + dtype: 'float16', + } + : 1.5 + ); + const validate = vi.fn((_value: number, provenance?: { atRoot(): unknown }) => { + expect(provenance?.atRoot()).toBeUndefined(); + }); + + await expect(protocol.call('module', 'bad', [], undefined, validate)).rejects.toThrow( + /must be an array at depth 0/ + ); + expect(validate).not.toHaveBeenCalled(); + bad = false; + await expect(protocol.call('module', 'plain', [], undefined, validate)).resolves.toBe( + 1.5 + ); + expect(validate).toHaveBeenCalledTimes(1); + }); }); }); diff --git a/test/runtime_conformance.test.ts b/test/runtime_conformance.test.ts index a95771c4..985b8aa8 100644 --- a/test/runtime_conformance.test.ts +++ b/test/runtime_conformance.test.ts @@ -356,12 +356,21 @@ class HttpReferenceBackend implements ConformanceBackend { const PYODIDE_CORE_HARNESS = `${BOOTSTRAP_PYTHON} import sys as __tywrap_driver_sys -for __tywrap_line in __tywrap_driver_sys.stdin: - __tywrap_line = __tywrap_line.strip() - if not __tywrap_line: - continue - __tywrap_driver_sys.stdout.write(__tywrap_dispatch(__tywrap_line) + '\\n') - __tywrap_driver_sys.stdout.flush() +import asyncio as __tywrap_driver_asyncio +import inspect as __tywrap_driver_inspect + +async def __tywrap_driver_main(): + for __tywrap_line in __tywrap_driver_sys.stdin: + __tywrap_line = __tywrap_line.strip() + if not __tywrap_line: + continue + __tywrap_result = __tywrap_dispatch(__tywrap_line) + if __tywrap_driver_inspect.isawaitable(__tywrap_result): + __tywrap_result = await __tywrap_result + __tywrap_driver_sys.stdout.write(__tywrap_result + '\\n') + __tywrap_driver_sys.stdout.flush() + +__tywrap_driver_asyncio.run(__tywrap_driver_main()) `; // The harness inlines the full ~31 KB bootstrap. Passing it via `python -c "..."` diff --git a/test/runtime_coroutines.test.ts b/test/runtime_coroutines.test.ts new file mode 100644 index 00000000..4aedfcfe --- /dev/null +++ b/test/runtime_coroutines.test.ts @@ -0,0 +1,704 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { delimiter, join } from 'node:path'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { pathToFileURL } from 'node:url'; +import { EventEmitter } from 'node:events'; +import type { ChildProcess } from 'node:child_process'; +import { NodeBridge } from '../src/runtime/node.js'; +import { PyodideTransport } from '../src/runtime/pyodide-transport.js'; +import { PooledTransport } from '../src/runtime/pooled-transport.js'; +import { SubprocessTransport } from '../src/runtime/subprocess-transport.js'; +import { RpcClient } from '../src/runtime/rpc-client.js'; +import type { Transport } from '../src/runtime/transport.js'; +import { clearRuntimeBridge, setRuntimeBridge } from '../src/runtime/index.js'; +import { + BridgeDisposedError, + BridgeExecutionError, + BridgeProtocolError, + BridgeTimeoutError, +} from '../src/runtime/errors.js'; +import { generate } from '../src/tywrap.js'; +import { isNodejs } from '../src/utils/runtime.js'; +import { PYTHON, PYTHON_AVAILABLE } from './helpers/python-probe.js'; + +const pythonPath = [ + join(process.cwd(), 'test/menagerie'), + join(process.cwd(), 'test/fixtures/python'), +].join(delimiter); +const nodeSuite = isNodejs() && PYTHON_AVAILABLE ? describe : describe.skip; + +nodeSuite('Coroutine RPC through Node', () => { + let bridge: NodeBridge | undefined; + + const createBridge = (timeoutMs = 5000): NodeBridge => + new NodeBridge({ + scriptPath: 'runtime/python_bridge.py', + pythonPath: PYTHON ?? undefined, + timeoutMs, + env: { PYTHONPATH: pythonPath }, + }); + + afterEach(async () => { + clearRuntimeBridge(); + await bridge?.dispose(); + bridge = undefined; + }); + + it('generates, imports, and executes asyncText', async () => { + const tempDir = await mkdtemp(join(process.cwd(), '.tmp-coroutine-')); + try { + await writeFile( + join(tempDir, 'coroutine_fixture.py'), + 'async def async_text() -> str:\n return "awaited"\n', + 'utf8' + ); + const outputDir = join(tempDir, 'generated'); + const generated = await generate({ + pythonModules: { coroutine_fixture: { typeHints: 'strict' } }, + pythonImportPath: [tempDir], + output: { dir: outputDir, format: 'esm', declaration: true, sourceMap: false }, + runtime: { node: { pythonPath: PYTHON ?? 'python3' } }, + performance: { caching: false, batching: false, compression: 'none' }, + } as never); + expect(generated.failures).toEqual([]); + expect(generated.warnings).toEqual([]); + const generatedPath = generated.written.find(path => path.endsWith('.generated.ts')); + expect(generatedPath).toBeDefined(); + const declarationPath = generated.written.find(path => path.endsWith('.generated.d.ts')); + expect(declarationPath).toBeDefined(); + expect(await readFile(generatedPath as string, 'utf8')).toMatch( + /^export async function asyncText\(\): Promise \{$/m + ); + expect(await readFile(declarationPath as string, 'utf8')).toMatch( + /^export function asyncText\(\): Promise;$/m + ); + + bridge = new NodeBridge({ + scriptPath: 'runtime/python_bridge.py', + pythonPath: PYTHON ?? undefined, + env: { PYTHONPATH: [tempDir, pythonPath].join(delimiter) }, + }); + setRuntimeBridge(bridge); + const mod = (await import(pathToFileURL(generatedPath as string).href)) as { + asyncText: () => Promise; + }; + expect(await mod.asyncText()).toBe('awaited'); + expect(await bridge.call('math', 'sqrt', [16])).toBe(4); + } finally { + await bridge?.dispose(); + bridge = undefined; + clearRuntimeBridge(); + await rm(tempDir, { recursive: true, force: true }); + } + }, 120000); + + it('preserves the Python exception envelope and traceback', async () => { + bridge = createBridge(); + try { + await bridge.call('async_module', 'raise_after_await', []); + throw new Error('Expected the async call to fail'); + } catch (error) { + expect(error).toBeInstanceOf(BridgeExecutionError); + expect((error as Error).message).toContain('ValueError: async failure'); + expect((error as BridgeExecutionError).traceback).toContain('raise_after_await'); + } + }); + + it('rejects both generator kinds without starting iteration', async () => { + bridge = createBridge(); + await expect(bridge.call('async_module', 'sync_generator', [2])).rejects.toThrow( + 'Generator results are not supported' + ); + await expect(bridge.call('async_module', 'async_generator', [2])).rejects.toThrow( + 'Async generator results are not supported' + ); + expect(await bridge.call('math', 'sqrt', [9])).toBe(3); + }); + + it('retires a timed-out worker and succeeds on a fresh process', async () => { + bridge = createBridge(1000); + const firstPid = await bridge.call('os', 'getpid', []); + await expect(bridge.call('async_module', 'delayed_value', [2])).rejects.toBeInstanceOf( + BridgeTimeoutError + ); + const nextPid = await bridge.call('os', 'getpid', []); + expect(nextPid).not.toBe(firstPid); + expect(await bridge.call('async_module', 'delayed_value', [0])).toBe('finished'); + }, 20000); + + it('disposes the process while a coroutine awaits', async () => { + bridge = createBridge(); + await bridge.call('os', 'getpid', []); + const pending = bridge.call('async_module', 'delayed_value', [3]); + const settled = pending.then( + () => new Error('Expected disposal to reject the call'), + error => error as Error + ); + await new Promise(resolve => setTimeout(resolve, 100)); + await bridge.dispose(); + expect(await settled).toBeInstanceOf(BridgeDisposedError); + }, 10000); +}); + +nodeSuite('Subprocess retirement boundary', () => { + it('keeps the process after an abort before send', async () => { + const transport = new SubprocessTransport({ + bridgeScript: 'runtime/python_bridge.py', + pythonPath: PYTHON ?? 'python3', + }); + const pidRequest = (id: number): string => + JSON.stringify({ + id, + protocol: 'tywrap/1', + method: 'call', + params: { module: 'os', functionName: 'getpid', args: [], kwargs: {} }, + }); + try { + const first = JSON.parse(await transport.send(pidRequest(1), 5000)) as { result: number }; + const controller = new AbortController(); + controller.abort(); + await expect(transport.send(pidRequest(2), 5000, controller.signal)).rejects.toBeInstanceOf( + BridgeTimeoutError + ); + expect(transport.requiresReplacement).toBe(false); + const second = JSON.parse(await transport.send(pidRequest(3), 5000)) as { result: number }; + expect(second.result).toBe(first.result); + } finally { + await transport.dispose(); + } + }, 15000); +}); + +nodeSuite('Subprocess retirement reaps the child', () => { + it('lets a responsive bridge exit without SIGKILL', async () => { + const transport = new SubprocessTransport({ + bridgeScript: 'runtime/python_bridge.py', + pythonPath: PYTHON ?? 'python3', + }); + try { + await transport.init(); + const child = (transport as unknown as { process: ChildProcess }).process; + const kill = vi.spyOn(child, 'kill'); + await transport.dispose(); + expect(kill).not.toHaveBeenCalledWith('SIGKILL'); + expect(child.exitCode != null || child.signalCode != null).toBe(true); + } finally { + await transport.dispose(); + } + }, 10_000); + + it('keeps a replacement healthy after late errors from the retired child', async () => { + const transport = new SubprocessTransport({ + bridgeScript: 'runtime/python_bridge.py', + pythonPath: PYTHON ?? 'python3', + }); + const internals = transport as unknown as { + process: ChildProcess | null; + processExited: boolean; + processError: Error | null; + needsRestart: boolean; + draining: boolean; + pending: Map void; reject: (error: Error) => void }>; + restartProcess: () => Promise; + }; + try { + await transport.init(); + const retired = internals.process; + expect(retired).not.toBeNull(); + expect(retired?.stdin).not.toBeNull(); + expect(retired?.stdout).not.toBeNull(); + expect(retired?.stderr).not.toBeNull(); + await internals.restartProcess(); + expect(internals.process).not.toBe(retired); + + expect(() => + retired?.stdout?.emit('error', new Error('late retired stdout error')) + ).not.toThrow(); + expect(() => + retired?.stderr?.emit('error', new Error('late retired stderr error')) + ).not.toThrow(); + + internals.draining = true; + retired?.stdin?.emit('drain'); + expect(internals.draining).toBe(true); + + const reject = vi.fn(); + internals.pending.set(900, { resolve: vi.fn(), reject }); + retired?.emit('error', new Error('late retired process error')); + retired?.stdin?.emit('error', new Error('late retired stdin error')); + + expect(reject).not.toHaveBeenCalled(); + expect(internals.processExited).toBe(false); + expect(internals.processError).toBeNull(); + expect(internals.needsRestart).toBe(false); + } finally { + internals.pending.delete(900); + await transport.dispose(); + } + }, 10_000); + + it('clears old backpressure without losing a reused request id', async () => { + const transport = new SubprocessTransport({ + bridgeScript: 'runtime/python_bridge.py', + pythonPath: PYTHON ?? 'python3', + writeQueueTimeoutMs: 150, + }); + const internals = transport as unknown as { + process: ChildProcess | null; + draining: boolean; + writeQueue: unknown[]; + }; + const pidRequest = (id: number): string => + JSON.stringify({ + id, + protocol: 'tywrap/1', + method: 'call', + params: { module: 'os', functionName: 'getpid', args: [], kwargs: {} }, + }); + try { + await transport.init(); + const oldChild = internals.process; + internals.draining = true; + const first = transport.send(pidRequest(901), 5000); + const firstRejected = expect(first).rejects.toThrow('stdout error'); + await vi.waitFor(() => expect(internals.writeQueue.length).toBe(1)); + oldChild?.stdout?.emit('error', new Error('old stdout failed')); + await firstRejected; + + const response = JSON.parse(await transport.send(pidRequest(901), 5000)) as { + result: number; + }; + expect(response.result).toBeTypeOf('number'); + expect(internals.process).not.toBe(oldChild); + expect(internals.writeQueue).toHaveLength(0); + } finally { + await transport.dispose(); + } + }, 10_000); + + it.skipIf(process.platform === 'win32')( + 'forces exit when Python ignores SIGTERM', + async () => { + const transport = new SubprocessTransport({ + bridgeScript: join(process.cwd(), 'test/fixtures/python/ignore_sigterm_bridge.py'), + pythonPath: PYTHON ?? 'python3', + }); + let child: ChildProcess | undefined; + try { + await transport.init(); + const internals = transport as unknown as { + process: ChildProcess; + stderrBuffer: string; + }; + child = internals.process; + await vi.waitFor(() => expect(internals.stderrBuffer).toContain('READY'), { + timeout: 5000, + }); + const kill = vi.spyOn(child, 'kill'); + + await expect(transport.send(request, 250)).rejects.toBeInstanceOf(BridgeTimeoutError); + await transport.dispose(); + + expect(kill).toHaveBeenCalledWith('SIGTERM'); + expect(kill).toHaveBeenCalledWith('SIGKILL'); + expect(child.signalCode).toBe('SIGKILL'); + } finally { + if (child && child.exitCode == null && child.signalCode == null) { + child.kill('SIGKILL'); + await new Promise(resolve => { + const timer = setTimeout(resolve, 1000); + child?.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + }); + } + await transport.dispose(); + } + }, + 10_000 + ); +}); + +describe('Subprocess cleanup retry', () => { + it('retains a child handle when kill fails and retries after disposal', async () => { + vi.useFakeTimers(); + let canExit = false; + const child = Object.assign(new EventEmitter(), { + stdin: Object.assign(new EventEmitter(), { end: () => undefined }), + stdout: new EventEmitter(), + stderr: new EventEmitter(), + exitCode: null as number | null, + signalCode: null as NodeJS.Signals | null, + killed: false, + kill: vi.fn((signal: NodeJS.Signals) => { + child.killed = true; + if (canExit && signal === 'SIGKILL') { + child.signalCode = 'SIGKILL'; + queueMicrotask(() => child.emit('exit', null, 'SIGKILL')); + } + return true; + }), + }); + const transport = new SubprocessTransport({ bridgeScript: 'unused' }); + const internals = transport as unknown as { _state: 'ready'; process: unknown }; + internals._state = 'ready'; + internals.process = child; + try { + const first = transport.dispose(); + expect(transport.dispose()).toBe(first); + await vi.advanceTimersByTimeAsync(2100); + await expect(first).rejects.toBeInstanceOf(BridgeProtocolError); + expect(transport.isDisposed).toBe(true); + expect(internals.process).toBe(child); + expect(child.kill).toHaveBeenCalledWith('SIGTERM'); + expect(child.kill).toHaveBeenCalledWith('SIGKILL'); + + canExit = true; + const retry = transport.dispose(); + await vi.advanceTimersByTimeAsync(1100); + await expect(retry).resolves.toBeUndefined(); + expect(internals.process).toBeNull(); + expect(child.signalCode).toBe('SIGKILL'); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('Subprocess partial-write abort', () => { + it('retires after the first frame, independent of timeout tombstones', async () => { + const controller = new AbortController(); + const write = vi.fn(() => { + controller.abort(); + return true; + }); + const stdin = Object.assign(new EventEmitter(), { write, end: () => undefined }); + const child = Object.assign(new EventEmitter(), { + stdin, + stdout: new EventEmitter(), + stderr: new EventEmitter(), + killed: false, + kill: () => { + child.killed = true; + queueMicrotask(() => child.emit('exit', 0, null)); + return true; + }, + }); + const transport = new SubprocessTransport({ bridgeScript: 'unused', maxLineLength: 64 }); + const internals = transport as unknown as { + _state: 'ready'; + process: unknown; + processExited: boolean; + timedOutRequests: { mark: (id: number) => void }; + }; + internals._state = 'ready'; + internals.processExited = false; + internals.process = child; + try { + await expect(transport.send(request, 1000, controller.signal)).rejects.toBeInstanceOf( + BridgeTimeoutError + ); + expect(write).toHaveBeenCalledTimes(1); + expect(transport.requiresReplacement).toBe(true); + + const baseline = Date.now(); + const clock = vi.spyOn(Date, 'now').mockReturnValue(baseline); + try { + for (let id = 0; id < 1001; id += 1) internals.timedOutRequests.mark(id); + clock.mockReturnValue(baseline + 11 * 60_000); + internals.timedOutRequests.mark(2000); + expect(internals.process).toBeNull(); + expect(transport.requiresReplacement).toBe(true); + } finally { + clock.mockRestore(); + } + } finally { + await transport.dispose(); + } + }); +}); + +describe('RPC default timeout', () => { + it('uses the configured default beyond 30 seconds', async () => { + vi.useFakeTimers(); + const transport: Transport = { + init: async () => undefined, + dispose: async () => undefined, + send: async () => + new Promise(resolve => { + setTimeout( + () => resolve(JSON.stringify({ id: 1, protocol: 'tywrap/1', result: 'ok' })), + 31_000 + ); + }), + capabilities: () => ({ + backend: 'subprocess', + supportsArrow: false, + supportsBinary: true, + supportsChunking: false, + supportsStreaming: false, + maxFrameBytes: Number.POSITIVE_INFINITY, + }), + get isReady() { + return true; + }, + get isDisposed() { + return false; + }, + }; + const client = new RpcClient({ transport, defaultTimeoutMs: 40_000 }); + try { + const call = client.sendMessage({ method: 'call', params: {} }); + await vi.advanceTimersByTimeAsync(31_000); + await expect(call).resolves.toBe('ok'); + } finally { + await client.dispose(); + vi.useRealTimers(); + } + }); +}); + +describe('Retired worker leases', () => { + function createFakePool( + onReplacementWorkerReady?: () => Promise, + firstDispose?: () => Promise + ) { + let created = 0; + const disposals: Array> = []; + const pool = new PooledTransport({ + minWorkers: 1, + maxWorkers: 1, + onReplacementWorkerReady, + createTransport: () => { + const index = created++; + const dispose = vi.fn(index === 0 && firstDispose ? firstDispose : async () => undefined); + disposals.push(dispose); + const worker: Transport & { requiresReplacement: boolean } = { + requiresReplacement: false, + init: async () => undefined, + dispose, + send: async () => { + if (index === 0) { + worker.requiresReplacement = true; + throw new BridgeTimeoutError('Operation timed out'); + } + return response; + }, + get isReady() { + return true; + }, + capabilities: () => ({ + backend: 'subprocess', + supportsArrow: false, + supportsBinary: true, + supportsChunking: false, + supportsStreaming: false, + maxFrameBytes: Number.POSITIVE_INFINITY, + }), + }; + return worker; + }, + }); + return { pool, disposals, count: () => created }; + } + + it('replaces a retired lease before serving the next request', async () => { + const warmup = vi.fn(async () => undefined); + const { pool, disposals, count } = createFakePool(warmup); + try { + await pool.init(); + await expect(pool.send(request, 100)).rejects.toBeInstanceOf(BridgeTimeoutError); + await vi.waitFor(() => expect(count()).toBe(2)); + expect(await pool.send(request, 100)).toBe(response); + expect(warmup).toHaveBeenCalledTimes(1); + expect(disposals[0]).toHaveBeenCalledTimes(1); + } finally { + await pool.dispose(); + } + }); + + it('holds the worker slot until retired cleanup succeeds', async () => { + const gate = deferred(); + const { pool, count } = createFakePool(undefined, () => gate.promise); + try { + await pool.init(); + await expect(pool.send(request, 100)).rejects.toBeInstanceOf(BridgeTimeoutError); + const next = pool.send(request, 100); + expect(count()).toBe(1); + expect(pool.workerCount).toBe(0); + + gate.resolve(undefined); + await expect(next).resolves.toBe(response); + expect(count()).toBe(2); + } finally { + gate.resolve(undefined); + await pool.dispose(); + } + }); + + it('blocks replacement after failed cleanup and retains a retryable worker', async () => { + const cleanupError = new BridgeProtocolError('Python process did not exit after SIGKILL'); + let attempts = 0; + const { pool, disposals, count } = createFakePool(undefined, async () => { + attempts++; + if (attempts < 3) { + throw cleanupError; + } + }); + await pool.init(); + await expect(pool.send(request, 100)).rejects.toBeInstanceOf(BridgeTimeoutError); + await expect(pool.send(request, 100)).rejects.toBe(cleanupError); + expect(count()).toBe(1); + expect(pool.workerCount).toBe(0); + await expect(pool.dispose()).rejects.toBe(cleanupError); + expect(disposals[0]).toHaveBeenCalledTimes(2); + await expect(pool.dispose()).resolves.toBeUndefined(); + expect(disposals[0]).toHaveBeenCalledTimes(3); + }); + + it('does not publish a replacement after disposal', async () => { + const started = deferred(); + const gate = deferred(); + const { pool, disposals } = createFakePool(async () => { + started.resolve(undefined); + await gate.promise; + }); + await pool.init(); + await expect(pool.send(request, 100)).rejects.toBeInstanceOf(BridgeTimeoutError); + await started.promise; + const closing = pool.dispose(); + expect(pool.dispose()).toBe(closing); + await closing; + gate.resolve(undefined); + await vi.waitFor(() => expect(disposals[1]).toHaveBeenCalledTimes(1)); + expect(pool.workerCount).toBe(0); + }); +}); + +interface Deferred { + promise: Promise; + resolve: (value: T) => void; + reject: (error: Error) => void; +} + +function deferred(): Deferred { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +const request = JSON.stringify({ + id: 41, + protocol: 'tywrap/1', + method: 'call', + params: { module: 'math', functionName: 'sqrt', args: [4], kwargs: {} }, +}); +const response = JSON.stringify({ id: 41, protocol: 'tywrap/1', result: 2 }); + +describe('Pyodide coroutine transport lifecycle', () => { + let transport: PyodideTransport | undefined; + + afterEach(async () => { + await transport?.dispose(); + transport = undefined; + delete (globalThis as { loadPyodide?: unknown }).loadPyodide; + }); + + function installPyodide(result: string | PromiseLike) { + const destroyTask = vi.fn(); + const destroyDispatch = vi.fn(); + const cancel = vi.fn(); + const dispatch = Object.assign(() => result, { destroy: destroyDispatch }); + const task = + typeof result === 'string' ? result : Object.assign(result, { destroy: destroyTask }); + const dispatchTask = Object.assign(() => task, { destroy: destroyDispatch }); + const globals = new Map([ + ['__tywrap_dispatch', typeof result === 'string' ? dispatch : dispatchTask], + ['__tywrap_cancel', cancel], + ]); + const loadPyodide = vi.fn(async () => ({ + runPython: () => undefined, + runPythonAsync: async () => undefined, + globals: { + get: (key: string) => globals.get(key), + set: (key: string, value: unknown) => globals.set(key, value), + }, + toPy: (value: unknown) => value, + loadPackage: async () => undefined, + })); + (globalThis as { loadPyodide?: unknown }).loadPyodide = loadPyodide; + return { cancel, destroyTask, destroyDispatch, loadPyodide }; + } + + it('does not start a pre-aborted call', async () => { + const mock = installPyodide(response); + transport = new PyodideTransport(); + const controller = new AbortController(); + controller.abort(); + await expect(transport.send(request, 1000, controller.signal)).rejects.toBeInstanceOf( + BridgeTimeoutError + ); + expect(mock.destroyDispatch).not.toHaveBeenCalled(); + expect(mock.cancel).not.toHaveBeenCalled(); + }); + + it('cancels on timeout and keeps proxies until the task settles', async () => { + const pending = deferred(); + const mock = installPyodide(pending.promise); + transport = new PyodideTransport(); + await expect(transport.send(request, 20)).rejects.toBeInstanceOf(BridgeTimeoutError); + expect(mock.cancel).toHaveBeenCalledWith(41); + expect(mock.destroyTask).not.toHaveBeenCalled(); + pending.reject(new Error('CancelledError')); + await new Promise(resolve => setTimeout(resolve, 0)); + expect(mock.destroyTask).toHaveBeenCalledTimes(1); + expect(mock.destroyDispatch).toHaveBeenCalledTimes(1); + }); + + it('cancels only the aborted request', async () => { + const pending = deferred(); + const mock = installPyodide(pending.promise); + transport = new PyodideTransport(); + await transport.init(); + const controller = new AbortController(); + const call = transport.send(request, 0, controller.signal); + await new Promise(resolve => setTimeout(resolve, 0)); + controller.abort(); + await expect(call).rejects.toBeInstanceOf(BridgeTimeoutError); + expect(mock.cancel).toHaveBeenCalledTimes(1); + expect(mock.cancel).toHaveBeenCalledWith(41); + pending.reject(new Error('CancelledError')); + await new Promise(resolve => setTimeout(resolve, 0)); + expect(mock.destroyTask).toHaveBeenCalledTimes(1); + }); + + it('rejects disposal during await and cleans up after settlement', async () => { + const pending = deferred(); + const mock = installPyodide(pending.promise); + transport = new PyodideTransport(); + await transport.init(); + const call = transport.send(request, 0); + await new Promise(resolve => setTimeout(resolve, 0)); + await transport.dispose(); + await expect(call).rejects.toBeInstanceOf(BridgeDisposedError); + expect(mock.cancel).toHaveBeenCalledWith(41); + expect(mock.destroyTask).not.toHaveBeenCalled(); + pending.reject(new Error('CancelledError')); + await new Promise(resolve => setTimeout(resolve, 0)); + expect(mock.destroyTask).toHaveBeenCalledTimes(1); + }); + + it('does not cancel a completed call at the timeout boundary', async () => { + const mock = installPyodide(Promise.resolve(response)); + transport = new PyodideTransport(); + expect(await transport.send(request, 20)).toBe(response); + await new Promise(resolve => setTimeout(resolve, 25)); + expect(mock.cancel).not.toHaveBeenCalled(); + expect(mock.destroyTask).toHaveBeenCalledTimes(1); + }); +}); diff --git a/test/runtime_pyodide_browser.conformance.ts b/test/runtime_pyodide_browser.conformance.ts new file mode 100644 index 00000000..64b9bbd7 --- /dev/null +++ b/test/runtime_pyodide_browser.conformance.ts @@ -0,0 +1,202 @@ +import { execFile } from 'node:child_process'; +import { createServer, type Server } from 'node:http'; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { promisify } from 'node:util'; + +import { chromium } from '@playwright/test'; +import { afterEach, describe, expect, it } from 'vitest'; + +const execFileAsync = promisify(execFile); +const repoRoot = resolve(process.cwd()); +const tempRoot = mkdtempSync(join(tmpdir(), 'tywrap-pyodide-browser-')); + +function isInside(child: string, parent: string): boolean { + const relation = relative(resolve(parent), resolve(child)); + return ( + relation === '' || + (!isAbsolute(relation) && relation !== '..' && !relation.startsWith(`..${sep}`)) + ); +} + +function contentType(path: string): string { + if (path.endsWith('.html')) return 'text/html; charset=utf-8'; + if (path.endsWith('.js') || path.endsWith('.mjs')) return 'text/javascript; charset=utf-8'; + if (path.endsWith('.json')) return 'application/json; charset=utf-8'; + if (path.endsWith('.wasm')) return 'application/wasm'; + if (path.endsWith('.data')) return 'application/octet-stream'; + return 'application/octet-stream'; +} + +async function run(command: string, args: string[], cwd: string): Promise { + try { + const { stdout } = await execFileAsync(command, args, { + cwd, + timeout: 180_000, + maxBuffer: 10 * 1024 * 1024, + }); + return stdout; + } catch (error: unknown) { + const failure = error as Error & { stdout?: string; stderr?: string; code?: number | string }; + throw new Error( + `${command} ${args.join(' ')} failed (${String(failure.code ?? 'unknown')}):\n` + + `stdout:\n${failure.stdout ?? ''}\nstderr:\n${failure.stderr ?? ''}`, + { cause: error } + ); + } +} + +function createStaticServer( + compiled: string, + installedPackage: string +): Promise<{ server: Server; origin: string }> { + return new Promise((resolveServer, reject) => { + const server = createServer((request, response) => { + const path = new URL(request.url ?? '/', 'http://localhost').pathname; + if (path === '/') { + response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); + response.end(` +`); + return; + } + + const roots: Array<[prefix: string, root: string]> = [ + ['/dist/', join(installedPackage, 'dist')], + ['/pyodide/', join(repoRoot, 'node_modules', 'pyodide')], + ['/generated/', compiled], + ]; + const route = roots.find(([prefix]) => path.startsWith(prefix)); + if (!route) { + response.writeHead(404).end(); + return; + } + const [prefix, root] = route; + const target = resolve(root, decodeURIComponent(path.slice(prefix.length))); + if (!isInside(target, root)) { + response.writeHead(403).end(); + return; + } + try { + response.writeHead(200, { 'content-type': contentType(target) }); + response.end(readFileSync(target)); + } catch { + response.writeHead(404).end(); + } + }); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + if (!address || typeof address === 'string') { + reject(new Error('browser smoke server has no TCP address')); + return; + } + resolveServer({ server, origin: `http://127.0.0.1:${address.port}` }); + }); + }); +} + +describe('real browser PyodideBridge', () => { + afterEach(() => { + rmSync(tempRoot, { recursive: true, force: true }); + }); + + it('loads the pinned local runtime and executes an actual generated wrapper in Chromium', async () => { + const generated = join(tempRoot, 'source'); + const compiled = join(tempRoot, 'compiled'); + writeFileSync( + join(tempRoot, 'package.json'), + JSON.stringify({ name: 'tywrap-browser-smoke', private: true, type: 'module' }), + 'utf8' + ); + const packOutput = await run( + 'npm', + ['pack', '--ignore-scripts', '--json', '--pack-destination', tempRoot], + repoRoot + ); + const pack = JSON.parse(packOutput) as Array<{ filename?: string }>; + if (!pack[0]?.filename) throw new Error('npm pack returned no filename'); + await run( + 'npm', + [ + 'install', + '--ignore-scripts', + '--legacy-peer-deps', + '--no-audit', + '--no-fund', + join(tempRoot, pack[0].filename), + ], + tempRoot + ); + const installedPackage = join(tempRoot, 'node_modules', 'tywrap'); + expect(existsSync(join(installedPackage, 'dist', 'runtime', 'index.js'))).toBe(true); + await run( + process.execPath, + [ + join(installedPackage, 'dist', 'cli.js'), + 'generate', + '--modules', + 'math', + '--runtime', + 'pyodide', + '--output-dir', + generated, + ], + tempRoot + ); + await run( + process.execPath, + [ + join(tempRoot, 'node_modules', 'typescript', 'lib', 'tsc.js'), + '--ignoreConfig', + '--target', + 'ES2022', + '--module', + 'ESNext', + '--moduleResolution', + 'bundler', + '--skipLibCheck', + '--outDir', + compiled, + join(generated, 'math.generated.ts'), + ], + tempRoot + ); + + const { server, origin } = await createStaticServer(compiled, installedPackage); + let browser: Awaited> | undefined; + try { + browser = await chromium.launch(); + const page = await browser.newPage(); + await page.goto(origin); + const result = (await page.evaluate( + `(async () => { + const { PyodideBridge } = await import('/dist/runtime/pyodide.js'); + const { clearRuntimeBridge, setRuntimeBridge } = await import('/dist/runtime/index.js'); + const math = await import('/generated/math.generated.js'); + const bridge = new PyodideBridge({ indexURL: location.origin + '/pyodide/' }); + try { + setRuntimeBridge({ + call: bridge.call.bind(bridge), + dispose: bridge.dispose.bind(bridge), + }); + return { + result: await math.sqrt(81), + pythonVersion: await bridge.call('platform', 'python_version', []), + }; + } finally { + clearRuntimeBridge(); + await bridge.dispose(); + } + })()` + )) as { result: number; pythonVersion: string }; + expect(result).toMatchObject({ result: 9 }); + expect(result.pythonVersion).toMatch(/^\d+\.\d+\.\d+/); + } finally { + await browser?.close(); + await new Promise((resolveClose, reject) => + server.close(error => (error ? reject(error) : resolveClose())) + ); + } + }, 240_000); +}); diff --git a/test/runtime_pyodide_real.conformance.ts b/test/runtime_pyodide_real.conformance.ts new file mode 100644 index 00000000..699e7055 --- /dev/null +++ b/test/runtime_pyodide_real.conformance.ts @@ -0,0 +1,225 @@ +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +import { loadPyodide } from 'pyodide'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { PyodideBridge } from '../src/runtime/pyodide.js'; +import { PyodideTransport } from '../src/runtime/pyodide-transport.js'; +import { clearRuntimeBridge, setRuntimeBridge } from 'tywrap/runtime'; +import { generate } from '../src/tywrap.js'; + +const indexURL = `${join(process.cwd(), 'node_modules', 'pyodide')}/`; + +describe('real PyodideBridge', () => { + let bridge: PyodideBridge | undefined; + + afterEach(async () => { + clearRuntimeBridge(); + await bridge?.dispose(); + bridge = undefined; + }); + + it('runs standard library, byte envelope, scientific JSON, and Python error cases', async () => { + bridge = new PyodideBridge({ indexURL, packages: ['numpy'] }); + + await expect(bridge.call('math', 'sqrt', [81])).resolves.toBe(9); + await expect(bridge.call('builtins', 'bytes', [[0, 1, 255]])).resolves.toEqual( + new Uint8Array([0, 1, 255]) + ); + await expect(bridge.call('numpy', 'array', [[1.5, -2.25]])).resolves.toEqual([1.5, -2.25]); + await expect(bridge.call('math', 'not_a_function', [])).rejects.toMatchObject({ + name: 'BridgeExecutionError', + message: expect.stringMatching(/AttributeError:.*not_a_function/), + traceback: expect.stringContaining('not_a_function'), + }); + }, 180_000); + + it('executes a generated asyncText wrapper through real Pyodide', async () => { + const tempDir = mkdtempSync(join(process.cwd(), '.tmp-pyodide-coroutine-')); + const globals = globalThis as typeof globalThis & { loadPyodide?: typeof loadPyodide }; + const previousLoader = globals.loadPyodide; + try { + writeFileSync( + join(tempDir, 'tywrap_async_text.py'), + 'import asyncio\nasync def async_text() -> str:\n await asyncio.sleep(0)\n return "awaited in WASM"\n', + 'utf8' + ); + const generated = await generate({ + pythonModules: { tywrap_async_text: { typeHints: 'strict' } }, + pythonImportPath: [tempDir], + output: { dir: join(tempDir, 'generated'), format: 'esm', declaration: true }, + performance: { caching: false, batching: false, compression: 'none' }, + } as never); + expect(generated.failures).toEqual([]); + expect(generated.warnings).toEqual([]); + const generatedPath = generated.written.find(path => path.endsWith('.generated.ts')); + expect(generatedPath).toBeDefined(); + const declarationPath = generated.written.find(path => path.endsWith('.generated.d.ts')); + expect(declarationPath).toBeDefined(); + expect(readFileSync(generatedPath as string, 'utf8')).toMatch( + /^export async function asyncText\(\): Promise \{$/m + ); + expect(readFileSync(declarationPath as string, 'utf8')).toMatch( + /^export function asyncText\(\): Promise;$/m + ); + + globals.loadPyodide = async options => { + const py = await loadPyodide(options); + py.runPython(` +import sys, types, asyncio +tywrap_async_text = types.ModuleType('tywrap_async_text') +async def async_text(): + await asyncio.sleep(0) + return 'awaited in WASM' +tywrap_async_text.async_text = async_text +sys.modules['tywrap_async_text'] = tywrap_async_text +`); + return py; + }; + + bridge = new PyodideBridge({ indexURL }); + setRuntimeBridge(bridge); + const wrapper = (await import(pathToFileURL(generatedPath as string).href)) as { + asyncText: () => Promise; + }; + await expect(wrapper.asyncText()).resolves.toBe('awaited in WASM'); + await expect(bridge.call('math', 'sqrt', [16])).resolves.toBe(4); + } finally { + clearRuntimeBridge(); + await bridge?.dispose(); + bridge = undefined; + if (previousLoader) { + globals.loadPyodide = previousLoader; + } else { + delete globals.loadPyodide; + } + rmSync(tempDir, { recursive: true, force: true }); + } + }, 180_000); + + it('cancels a timed-out coroutine and accepts the next real Pyodide request', async () => { + const globals = globalThis as typeof globalThis & { loadPyodide?: typeof loadPyodide }; + const previousLoader = globals.loadPyodide; + const transport = new PyodideTransport({ indexURL }); + let py: Awaited> | undefined; + const request = (id: number, module: string, functionName: string, args: unknown[]): string => + JSON.stringify({ + id, + protocol: 'tywrap/1', + method: 'call', + params: { module, functionName, args, kwargs: {} }, + }); + + try { + globals.loadPyodide = async options => { + py = await loadPyodide(options); + py.runPython(` +import sys, types, asyncio +tywrap_slow = types.ModuleType('tywrap_slow') +async def slow(): + await asyncio.sleep(10) + return 'too late' +tywrap_slow.slow = slow +sys.modules['tywrap_slow'] = tywrap_slow +`); + return py; + }; + + await transport.init(); + const settlements: string[] = []; + const first = transport.send(request(71, 'tywrap_slow', 'slow', []), 100).then( + () => settlements.push('resolved'), + error => { + settlements.push('rejected'); + return error as Error; + } + ); + await expect(first).resolves.toMatchObject({ name: 'BridgeTimeoutError' }); + + await vi.waitFor( + () => { + expect(py?.runPython('len(__tywrap_tasks)')).toBe(0); + expect( + (transport as unknown as { activeCalls: Map }).activeCalls.size + ).toBe(0); + }, + { timeout: 5000 } + ); + + const next = JSON.parse(await transport.send(request(71, 'math', 'sqrt', [16]), 5000)) as { + result: number; + }; + expect(next.result).toBe(4); + expect(settlements).toEqual(['rejected']); + expect(py?.runPython('len(__tywrap_tasks)')).toBe(0); + } finally { + await transport.dispose(); + if (previousLoader) globals.loadPyodide = previousLoader; + else delete globals.loadPyodide; + } + }, 180_000); + + it('fails explicitly when Pyodide cannot load a requested package', async () => { + bridge = new PyodideBridge({ indexURL, packages: ['tywrap-package-that-does-not-exist'] }); + await expect(bridge.call('math', 'sqrt', [4])).rejects.toThrow(); + }, 180_000); + + it('requires local runtime assets before starting WASM', () => { + for (const name of [ + 'pyodide.mjs', + 'pyodide.asm.js', + 'pyodide.asm.wasm', + 'python_stdlib.zip', + 'pyodide-lock.json', + ]) { + if (!existsSync(join(indexURL, name))) { + throw new Error(`Required Pyodide runtime asset is missing: ${name}`); + } + } + }); + + it('reports a bootstrap failure and disposes the failed bridge', async () => { + const globals = globalThis as typeof globalThis & { loadPyodide?: typeof loadPyodide }; + const previousLoader = globals.loadPyodide; + let wasmLoaded = false; + let bootstrapAttempted = false; + try { + globals.loadPyodide = async options => { + const py = await loadPyodide(options); + wasmLoaded = true; + return new Proxy(py, { + get(target, property, receiver) { + if (property === 'runPythonAsync') { + return async (code: string) => { + bootstrapAttempted = code.includes('tywrap_bridge_core'); + return target.runPythonAsync( + `raise RuntimeError("bootstrap failure fixture")\n${code}` + ); + }; + } + return Reflect.get(target, property, receiver); + }, + }); + }; + bridge = new PyodideBridge({ indexURL }); + await expect(bridge.init()).rejects.toThrow('bootstrap failure fixture'); + expect(wasmLoaded).toBe(true); + expect(bootstrapAttempted).toBe(true); + expect(bridge.isReady).toBe(false); + await bridge.dispose(); + expect(bridge.isDisposed).toBe(true); + } finally { + if (previousLoader) globals.loadPyodide = previousLoader; + else delete globals.loadPyodide; + } + }, 180_000); + + it('rejects calls after disposal', async () => { + bridge = new PyodideBridge({ indexURL }); + await expect(bridge.call('math', 'sqrt', [4])).resolves.toBe(2); + await bridge.dispose(); + await expect(bridge.call('math', 'sqrt', [4])).rejects.toThrow(); + }, 180_000); +}); diff --git a/test/runtime_return_validation.test.ts b/test/runtime_return_validation.test.ts index 033bd349..d0c86043 100644 --- a/test/runtime_return_validation.test.ts +++ b/test/runtime_return_validation.test.ts @@ -3,11 +3,13 @@ import type { AddressInfo } from 'node:net'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { BridgeValidationError } from '../src/runtime/errors.js'; +import { DecodedProvenance } from '../src/runtime/decoded-provenance.js'; import { HttpBridge } from '../src/runtime/http.js'; import { NodeBridge } from '../src/runtime/node.js'; import { createReturnValidator, describeReceivedShape, + selectOverloadReturnValidator, tagDecodedShape, type ReturnSchema, } from '../src/runtime/validators.js'; @@ -26,6 +28,133 @@ describe('generated return validators', () => { expect(validator(42)).toBe(42); }); + it('checks the value contract number constraints at nested paths', () => { + const validator = createReturnValidator( + { + kind: 'record', + values: { kind: 'primitive', type: 'number', constraint: 'safe-integer' }, + }, + 'fixture.counts' + ); + expect(validator({ count: 42 })).toEqual({ count: 42 }); + expect(() => validator({ count: 1.5 })).toThrow(BridgeValidationError); + expect(() => validator({ count: Number.MAX_SAFE_INTEGER + 1 })).toThrow(BridgeValidationError); + }); + + it('requires bigint at each exact integer position', () => { + const validator = createReturnValidator( + { + kind: 'record', + fields: { + values: { + schema: { kind: 'array', element: { kind: 'primitive', type: 'bigint' } }, + }, + }, + }, + 'fixture.exactValues' + ); + expect(validator({ values: [1n, 18446744073709551617n] })).toEqual({ + values: [1n, 18446744073709551617n], + }); + expect(() => validator({ values: [1, 2n] })).toThrow(BridgeValidationError); + expect(() => validator({ values: ['1'] })).toThrow(BridgeValidationError); + const leaf = createReturnValidator({ kind: 'primitive', type: 'bigint' }, 'fixture.exactValue'); + expect(() => leaf('1')).toThrow(/expected bigint, received string/); + }); + + it('requires per-call provenance for a scalar float16 ndarray', () => { + const validate = createReturnValidator( + { kind: 'marker', marker: 'ndarray', dims: 0, dtype: 'float16' }, + 'fixture.scalar' + ); + const valid = new DecodedProvenance(); + valid.recordRoot({ marker: 'ndarray', dims: 0, dtype: 'float16' }); + const wrongDtype = new DecodedProvenance(); + wrongDtype.recordRoot({ marker: 'ndarray', dims: 0, dtype: 'float32' }); + const wrongShape = new DecodedProvenance(); + wrongShape.recordRoot({ marker: 'ndarray', dims: 1, dtype: 'float16' }); + + expect(() => validate(1.5)).toThrow(BridgeValidationError); + expect(validate(1.5, valid)).toBe(1.5); + expect(() => validate(1.5, wrongDtype)).toThrow(BridgeValidationError); + expect(() => validate(1.5, wrongShape)).toThrow(BridgeValidationError); + expect(validate(1.5, valid)).toBe(1.5); + }); + + it('checks nested scalar proofs at array indices and record keys', () => { + const scalar = { kind: 'marker', marker: 'ndarray', dims: 0, dtype: 'float16' } as const; + const rows = [[1.5]]; + const result = { rows, scalar: 1.5 }; + const proof = new DecodedProvenance(); + proof.recordChild(rows[0]!, 0, { marker: 'ndarray', dims: 0, dtype: 'float16' }); + proof.recordChild(result, 'scalar', { marker: 'ndarray', dims: 0, dtype: 'float16' }); + const validate = createReturnValidator( + { + kind: 'record', + fields: { + rows: { schema: { kind: 'array', element: { kind: 'tuple', elements: [scalar] } } }, + scalar: { schema: scalar }, + }, + }, + 'fixture.nestedScalar' + ); + expect(validate(result, proof)).toBe(result); + expect(() => validate(result)).toThrow(BridgeValidationError); + + const stringIndex = new DecodedProvenance(); + stringIndex.recordChild(rows[0]!, '0', { marker: 'ndarray', dims: 0, dtype: 'float16' }); + stringIndex.recordChild(result, 'scalar', { marker: 'ndarray', dims: 0, dtype: 'float16' }); + expect(validate(result, stringIndex)).toBe(result); + + const wrongIndex = new DecodedProvenance(); + wrongIndex.recordChild(rows[0]!, 1, { marker: 'ndarray', dims: 0, dtype: 'float16' }); + wrongIndex.recordChild(result, 'scalar', { marker: 'ndarray', dims: 0, dtype: 'float16' }); + expect(() => validate(result, wrongIndex)).toThrow(BridgeValidationError); + + const other = { rows: [[1.5]], scalar: 1.5 }; + expect(() => validate(other, proof)).toThrow(BridgeValidationError); + }); + + it('uses declaration order when an optional-arity overload also matches', () => { + const stringValue = { kind: 'primitive', type: 'string' } as const; + const integerValue = { kind: 'primitive', type: 'number', constraint: 'safe-integer' } as const; + const overloads = [ + { + parameters: [ + { name: 'value', kind: 'positional-or-keyword', optional: false, value: stringValue }, + ], + result: stringValue, + selectable: true, + }, + { + parameters: [ + { name: 'value', kind: 'positional-or-keyword', optional: false, value: stringValue }, + { name: 'base', kind: 'positional-or-keyword', optional: true, value: integerValue }, + ], + result: integerValue, + selectable: true, + }, + ] as const; + const fallback = createReturnValidator({ kind: 'any' }, 'fixture.ambiguous'); + const oneArg = selectOverloadReturnValidator( + overloads, + ['key'], + undefined, + fallback, + 'fixture.ambiguous' + ); + const twoArgs = selectOverloadReturnValidator( + overloads, + ['key', 2], + undefined, + fallback, + 'fixture.ambiguous' + ); + expect(() => oneArg(4)).toThrow(BridgeValidationError); + expect(oneArg('text')).toBe('text'); + expect(twoArgs(4)).toBe(4); + }); + it('checks unions, optionals, tuples, TypedDict records, and no-op schemas', () => { const schema: ReturnSchema = { kind: 'tuple', @@ -220,7 +349,17 @@ describe('return validator bridge propagation', () => { try { await expect(bridge.call('math', 'sqrt', [16], undefined, validate)).resolves.toBe(4); expect(validate).toHaveBeenCalledOnce(); - expect(validate).toHaveBeenCalledWith(4); + expect(validate).toHaveBeenCalledWith(4, expect.any(DecodedProvenance)); + const [, provenance] = validate.mock.calls[0] as unknown as [number, DecodedProvenance]; + expect(provenance.atRoot()).toBeUndefined(); + + const reject = vi.fn((_value: number) => { + throw new Error('one-argument validator rejected the value'); + }); + await expect(bridge.call('math', 'sqrt', [16], undefined, reject)).rejects.toThrow( + 'one-argument validator rejected the value' + ); + expect(reject).toHaveBeenCalledOnce(); } finally { await new Promise((resolve, reject) => server.close(error => (error ? reject(error) : resolve())) diff --git a/test/transport-pool.test.ts b/test/transport-pool.test.ts index cef32f12..4c523e9c 100644 --- a/test/transport-pool.test.ts +++ b/test/transport-pool.test.ts @@ -748,6 +748,7 @@ describe('PooledTransport', () => { removeWorker(worker: TransportLease): void; } ).removeWorker(worker); + await vi.waitFor(() => expect(transports).toHaveLength(2)); await pool.dispose(); await new Promise(resolve => setTimeout(resolve, 100)); @@ -779,6 +780,78 @@ describe('PooledTransport', () => { expect(transports).toHaveLength(1); expect(transports[0]?.disposeCalled).toBe(true); }); + + it('retains a late worker when its cleanup fails after pool disposal', async () => { + let releaseInit!: () => void; + const initGate = new Promise(resolve => { + releaseInit = resolve; + }); + const cleanupError = new BridgeProtocolError('Late worker cleanup failed'); + const transport = new MockTransport(); + let disposalAttempts = 0; + transport.init = async () => { + await initGate; + transport.initCalled = true; + }; + transport.dispose = async () => { + disposalAttempts++; + if (disposalAttempts === 1) { + throw cleanupError; + } + transport.disposeCalled = true; + }; + pool = new PooledTransport({ createTransport: () => transport, maxWorkers: 1 }); + + await pool.init(); + const acquisition = pool.acquire().then( + () => undefined, + error => error as Error + ); + await pool.dispose(); + releaseInit(); + await expect(acquisition).resolves.toBe(cleanupError); + expect(disposalAttempts).toBe(1); + await expect(pool.dispose()).resolves.toBeUndefined(); + expect(disposalAttempts).toBe(2); + expect(transport.disposeCalled).toBe(true); + }); + + it.each(['init', 'warmup'] as const)( + 'retains an unpublished worker after failed %s cleanup', + async stage => { + const transport = new MockTransport(); + let disposalAttempts = 0; + const failure = new Error(`${stage} failed`); + if (stage === 'init') { + transport.init = async () => { + throw failure; + }; + } + transport.dispose = async () => { + disposalAttempts++; + if (disposalAttempts === 1) { + throw new BridgeProtocolError('Worker cleanup failed'); + } + transport.disposeCalled = true; + }; + pool = new PooledTransport({ + createTransport: () => transport, + minWorkers: 1, + maxWorkers: 1, + onWorkerReady: async () => { + if (stage === 'warmup') { + throw failure; + } + }, + }); + + await expect(pool.init()).rejects.toThrow(); + expect(disposalAttempts).toBe(1); + await expect(pool.dispose()).resolves.toBeUndefined(); + expect(disposalAttempts).toBe(2); + expect(transport.disposeCalled).toBe(true); + } + ); }); // =========================================================================== diff --git a/test/transport.test.ts b/test/transport.test.ts index 2540fe93..f8e17470 100644 --- a/test/transport.test.ts +++ b/test/transport.test.ts @@ -1461,7 +1461,7 @@ describe('PyodideTransport', () => { const message = JSON.stringify(createValidMessage()); await expect(transport.send(message, 1000)).rejects.toThrow( - /Invalid JSON response from Python/ + /Invalid response from Python: missing numeric id/ ); }); }); diff --git a/test/value_contracts.test.ts b/test/value_contracts.test.ts new file mode 100644 index 00000000..71a7eaed --- /dev/null +++ b/test/value_contracts.test.ts @@ -0,0 +1,307 @@ +import { readFileSync } from 'node:fs'; +import { afterEach, describe, expect, it } from 'vitest'; +import { BridgeCodec } from '../src/runtime/bridge-codec.js'; +import { DecodedProvenance } from '../src/runtime/decoded-provenance.js'; +import { + MAX_SAFE_JSON_INTEGER, + VALUE_CONTRACT_REVISION, + isSafeJsonInteger, +} from '../src/contracts/value-contract.js'; +import { + clearArrowDecoder, + decodeValue, + decodeValueAsync, + registerArrowDecoder, + type ArrowTable, +} from '../src/utils/codec.js'; + +const specification = JSON.parse( + readFileSync(new URL('../docs/maintainers/value-contracts.v2.json', import.meta.url), 'utf8') +) as { + revision: number; + rules: { + integer: { minimum: number; maximum: number }; + bytes: { decodedAs: string }; + }; +}; +const fixtures = JSON.parse( + readFileSync( + new URL('../docs/maintainers/value-contract-fixtures.v2.json', import.meta.url), + 'utf8' + ) +) as { + revision: number; + bytesCases: readonly { + logicalHex: string; + requestEnvelope: object; + responseEnvelope: object; + decodedAs: string; + }[]; + binary16Cases: readonly { wordHex: string; outcome: string }[]; +}; + +function referenceBinary16(bits: number): number { + const sign = (bits & 0x8000) << 16; + let exponent = (bits >>> 10) & 0x1f; + let fraction = bits & 0x03ff; + let floatBits: number; + + if (exponent === 0 && fraction !== 0) { + exponent = -14; + while ((fraction & 0x0400) === 0) { + fraction <<= 1; + exponent -= 1; + } + fraction &= 0x03ff; + floatBits = sign | ((exponent + 127) << 23) | (fraction << 13); + } else if (exponent === 0) { + floatBits = sign; + } else { + floatBits = sign | ((exponent + 112) << 23) | (fraction << 13); + } + + const view = new DataView(new ArrayBuffer(4)); + view.setUint32(0, floatBits, true); + return view.getFloat32(0, true); +} + +function envelope(shape: number[]): object { + return { + __tywrap__: 'ndarray', + codecVersion: 1, + encoding: 'arrow', + b64: 'AA==', + shape, + dtype: 'float16', + }; +} + +function registerWords(words: readonly number[]): void { + registerArrowDecoder( + () => + ({ + getChildAt: () => ({ toArray: () => Uint16Array.from(words) }), + }) as ArrowTable + ); +} + +afterEach(() => clearArrowDecoder()); + +describe('frozen value policy', () => { + it('keeps the TypeScript safe-integer range equal to the JSON specification', () => { + expect(VALUE_CONTRACT_REVISION).toBe(specification.revision); + expect(fixtures.revision).toBe(specification.revision); + expect(MAX_SAFE_JSON_INTEGER).toBe(specification.rules.integer.maximum); + expect(-MAX_SAFE_JSON_INTEGER).toBe(specification.rules.integer.minimum); + expect(isSafeJsonInteger(MAX_SAFE_JSON_INTEGER)).toBe(true); + expect(isSafeJsonInteger(-MAX_SAFE_JSON_INTEGER)).toBe(true); + expect(isSafeJsonInteger(2 ** 53)).toBe(false); + expect(isSafeJsonInteger(-(2 ** 53))).toBe(false); + expect(isSafeJsonInteger(1.5)).toBe(false); + }); + + it('matches the shared bytes request and response fixtures', async () => { + const codec = new BridgeCodec(); + expect(specification.rules.bytes.decodedAs).toBe('JavaScript Uint8Array'); + for (const fixture of fixtures.bytesCases) { + const bytes = Uint8Array.from(Buffer.from(fixture.logicalHex, 'hex')); + const request = JSON.parse(codec.encodeRequest({ value: bytes })); + expect(request.value).toEqual(fixture.requestEnvelope); + + const decoded = await codec.decodeResponseAsync( + JSON.stringify({ id: 1, protocol: 'tywrap/1', result: fixture.responseEnvelope }) + ); + expect(decoded).toBeInstanceOf(Uint8Array); + expect([...decoded]).toEqual([...bytes]); + expect(`Uint8Array[${[...decoded].join(',')}]`).toBe(fixture.decodedAs); + } + }); +}); + +describe('Arrow float16 value contract', () => { + it('matches the fixed proof fixtures', () => { + for (const fixture of fixtures.binary16Cases) { + registerWords([Number.parseInt(fixture.wordHex, 16)]); + if (fixture.outcome === 'reject') { + expect(() => decodeValue(envelope([1]))).toThrow(/non-finite float16/); + } else { + const decoded = decodeValue(envelope([1])) as number[]; + expect(Object.is(decoded[0], Number(fixture.outcome)), fixture.wordHex).toBe(true); + } + } + }); + + it('matches an independent float32 bit reference for every finite binary16 word', () => { + const words = Array.from({ length: 0x10000 }, (_, word) => word).filter( + word => ((word >>> 10) & 0x1f) !== 0x1f + ); + registerWords(words); + const decoded = decodeValue(envelope([words.length])) as number[]; + expect(decoded).toHaveLength(words.length); + for (let index = 0; index < words.length; index += 1) { + if (!Object.is(decoded[index], referenceBinary16(words[index] as number))) { + throw new Error(`binary16 word ${words[index]} decoded incorrectly`); + } + } + expect(Object.is(decoded[0], 0)).toBe(true); + expect(Object.is(decoded[words.indexOf(0x8000)], -0)).toBe(true); + expect(decoded[words.indexOf(0x0001)]).toBe(2 ** -24); + expect(decoded[words.indexOf(0x7bff)]).toBe(65504); + expect(decoded[words.indexOf(0xfbff)]).toBe(-65504); + }); + + it('decodes scalar and multidimensional arrays before reshaping', () => { + registerWords([0x3e00]); + expect(decodeValue(envelope([]))).toBe(1.5); + registerWords([0x3e00, 0xc080, 0x0001, 0x8000]); + expect(decodeValue(envelope([2, 2]))).toEqual([ + [1.5, -2.25], + [2 ** -24, -0], + ]); + }); + + it('carries Arrow scalar float16 proof with the decoded number', async () => { + registerWords([0x3e00]); + const provenance = new DecodedProvenance(); + expect(await decodeValueAsync(envelope([]), provenance)).toBe(1.5); + expect(provenance.atRoot()).toEqual({ marker: 'ndarray', dims: 0, dtype: 'float16' }); + }); + + it('uses the ndarray rule inside nested Torch and record values', async () => { + registerWords([0x3e00, 0xc080]); + const value = { + outer: [ + { + __tywrap__: 'torch.tensor', + codecVersion: 1, + encoding: 'ndarray', + value: envelope([2]), + shape: [2], + dtype: 'torch.float16', + device: 'cpu', + }, + ], + }; + await expect(decodeValueAsync(value)).resolves.toEqual({ + outer: [{ data: [1.5, -2.25], shape: [2], dtype: 'torch.float16', device: 'cpu' }], + }); + }); + + it.each([ + { shape: [], encoding: 'json' }, + { shape: [1], encoding: 'json' }, + { shape: [], encoding: 'arrow' }, + { shape: [1], encoding: 'arrow' }, + ] as const)( + 'requires a matching nested dtype for Torch float16 shape $shape with $encoding data', + async ({ shape, encoding }) => { + registerWords([0x3e00]); + const nested = { + __tywrap__: 'ndarray', + codecVersion: 1, + encoding, + shape, + dtype: 'float16', + ...(encoding === 'arrow' ? { b64: 'AA==' } : { data: shape.length ? [1.5] : 1.5 }), + }; + const tensor = { + __tywrap__: 'torch.tensor', + codecVersion: 1, + encoding: 'ndarray', + value: nested, + shape, + dtype: 'torch.float16', + device: 'cpu', + }; + + await expect(decodeValueAsync(tensor)).resolves.toMatchObject({ + data: shape.length ? [1.5] : 1.5, + dtype: 'torch.float16', + }); + await expect( + decodeValueAsync({ ...tensor, value: { ...nested, dtype: 'float32' } }) + ).rejects.toThrow(/value\.dtype.*must be "float16".*"torch\.float16"/); + } + ); + + it('requires the nested version 1 envelope for Torch float16', async () => { + await expect( + decodeValueAsync({ + __tywrap__: 'torch.tensor', + codecVersion: 1, + encoding: 'ndarray', + shape: [], + dtype: 'torch.float16', + value: { + __tywrap__: 'ndarray', + encoding: 'json', + shape: [], + dtype: 'float16', + data: 1.5, + }, + }) + ).rejects.toThrow(/float16 value must use ndarray codecVersion 1/); + }); + + it.each([0x7c00, 0xfc00, 0x7e00])('rejects non-finite word %s', word => { + registerWords([word]); + expect(() => decodeValue(envelope([1]))).toThrow(/non-finite float16 value at b64\[0\]/); + }); + + it('rejects a mismatched Arrow type or null storage', () => { + registerArrowDecoder( + () => + ({ + getChildAt: () => ({ + type: 'Int16', + nullCount: 0, + toArray: () => Uint16Array.of(0x3e00), + }), + }) as ArrowTable + ); + expect(() => decodeValue(envelope([1]))).toThrow(/column type does not match/); + registerArrowDecoder( + () => + ({ + getChildAt: () => ({ + type: 'Float16', + nullCount: 1, + toArray: () => Uint16Array.of(0), + }), + }) as ArrowTable + ); + expect(() => decodeValue(envelope([1]))).toThrow(/column contains null values/); + }); + + it('keeps JSON fallback numeric and Arrow int64 exact', () => { + expect( + decodeValue({ + __tywrap__: 'ndarray', + codecVersion: 1, + encoding: 'json', + data: [1.5, -2.25], + shape: [2], + dtype: 'float16', + }) + ).toEqual([1.5, -2.25]); + + registerArrowDecoder( + () => + ({ + getChildAt: () => ({ + toArray: () => BigInt64Array.of(-9223372036854775808n, 9223372036854775807n), + }), + }) as ArrowTable + ); + expect( + decodeValue({ + __tywrap__: 'ndarray', + codecVersion: 1, + encoding: 'arrow', + b64: 'AA==', + shape: [2], + dtype: 'int64', + }) + ).toEqual([-9223372036854775808n, 9223372036854775807n]); + }); +}); diff --git a/test/value_contracts_v3.test.ts b/test/value_contracts_v3.test.ts new file mode 100644 index 00000000..9f32e43e --- /dev/null +++ b/test/value_contracts_v3.test.ts @@ -0,0 +1,110 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; +import { + VALUE_CONTRACT_REVISION, + VALUE_CONTRACT_V3_REVISION, + type ExactIntegerValueContract, + type ValueContractV3, +} from '../src/contracts/value-contract.js'; + +const specification = JSON.parse( + readFileSync(new URL('../docs/maintainers/value-contracts.v3.json', import.meta.url), 'utf8') +) as { + revision: number; + base: { file: string; revision: number; hashCanonicalization: string; sha256: string }; + exactIntegerEnvelopeCodecVersion: number; + callPolicy: string; + requiredCapability: string; + rules: { + 'integer-exact': { + contract: ExactIntegerValueContract; + decimalGrammar: string; + maximumDigitsWithoutSign: number; + }; + }; +}; + +const fixtures = JSON.parse( + readFileSync( + new URL('../docs/maintainers/value-contract-fixtures.v3.json', import.meta.url), + 'utf8' + ) +) as { + revision: number; + integerCases: readonly { + logicalDecimal: string; + envelope: { __tywrap__: string; codecVersion: number; encoding: string; value: string }; + }[]; + rejectedDecimals: readonly string[]; +}; + +describe('exact integer value policy', () => { + it('pins revision 3 to the unchanged revision-2 source', () => { + const base = readFileSync( + new URL(`../docs/maintainers/${specification.base.file}`, import.meta.url) + ); + const baseRevision = JSON.parse(base.toString('utf8')) as { revision: number }; + expect(specification.revision).toBe(VALUE_CONTRACT_V3_REVISION); + expect(fixtures.revision).toBe(VALUE_CONTRACT_V3_REVISION); + expect(specification.base.revision).toBe(VALUE_CONTRACT_REVISION); + expect(baseRevision.revision).toBe(VALUE_CONTRACT_REVISION); + expect(specification.base.hashCanonicalization).toBe('UTF-8 with LF line endings'); + const canonical = base.toString('utf8').replace(/\r\n/g, '\n'); + expect(createHash('sha256').update(canonical, 'utf8').digest('hex')).toBe( + specification.base.sha256 + ); + }); + + it('keeps semantic revision, envelope version, and call policy distinct', () => { + expect(specification.revision).toBe(3); + expect(specification.exactIntegerEnvelopeCodecVersion).toBe(2); + expect(specification.callPolicy).toBe('bigint-v2'); + expect(specification.requiredCapability).toBe('exactIntegerDecimalV2'); + expect(specification.rules['integer-exact'].contract).toEqual({ + kind: 'integer-exact', + wire: 'decimal-string-envelope', + decodedAs: 'bigint', + constraint: 'exact-integer', + }); + }); + + it('permits exact integer leaves inside the shared composite shapes', () => { + const nested: ValueContractV3 = { + kind: 'record', + wire: 'json', + decodedAs: 'object', + fields: [ + { + name: 'values', + required: true, + value: { + kind: 'sequence', + wire: 'json', + decodedAs: 'array', + item: specification.rules['integer-exact'].contract, + }, + }, + ], + }; + expect(nested.fields[0]?.value.kind).toBe('sequence'); + }); + + it('fixes the canonical decimal grammar and proof values', () => { + const rule = specification.rules['integer-exact']; + const decimal = new RegExp(rule.decimalGrammar); + expect(rule.maximumDigitsWithoutSign).toBe(4096); + for (const fixture of fixtures.integerCases) { + expect(decimal.test(fixture.logicalDecimal)).toBe(true); + expect(fixture.envelope).toEqual({ + __tywrap__: 'integer', + codecVersion: 2, + encoding: 'decimal', + value: fixture.logicalDecimal, + }); + } + for (const value of fixtures.rejectedDecimals) { + expect(decimal.test(value)).toBe(false); + } + }); +}); diff --git a/test/value_extensions_generated_integer.test.ts b/test/value_extensions_generated_integer.test.ts new file mode 100644 index 00000000..3a54053f --- /dev/null +++ b/test/value_extensions_generated_integer.test.ts @@ -0,0 +1,444 @@ +import { execFileSync, spawnSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { delimiter, join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import ts from 'typescript'; +import { describe, expect, it } from 'vitest'; +import { + compileContract, + DEFAULT_CALLABLE_CAPABILITIES, + DEFAULT_VALUE_CONVERSION, + EXACT_INTEGER_VALUE_CONVERSION, + type CompiledContract, +} from '../src/core/callable-compiler.js'; +import { CodeGenerator } from '../src/core/generator.js'; +import { validateIrContract } from '../src/core/ir-contract.js'; +import { transformIrToTsModel } from '../src/core/ir-model.js'; +import { BridgeValidationError } from '../src/runtime/errors.js'; +import { clearRuntimeBridge, setRuntimeBridge } from 'tywrap/runtime'; +import type { PythonModule } from '../src/types/index.js'; +import { PYTHON, PYTHON_AVAILABLE } from './helpers/python-probe.js'; +import { + decodeExactResponse, + encodeExactRequest, + type PrototypeContract, +} from './prototypes/value_extensions.js'; +import { toExactPrototypeContract } from './prototypes/value_contract_v3_adapter.js'; + +const fixtureDir = join(process.cwd(), 'test', 'fixtures', 'python'); +const fixturePath = join(fixtureDir, 'value_contract_exact_integer.py'); +const pythonAdapter = join(process.cwd(), 'test', 'prototypes', 'value_exact_call.py'); +const pythonEnvironment = { + ...process.env, + PYTHONPATH: [ + fixtureDir, + join(process.cwd(), 'tywrap_ir'), + join(process.cwd(), 'test', 'prototypes'), + process.env.PYTHONPATH, + ] + .filter(Boolean) + .join(delimiter), +}; + +interface ExactInvocationDescriptor { + requiredCapability: 'exactIntegerDecimalV2'; + valuePolicy: { integer: 'bigint-v2' }; + args: PrototypeContract; + result: PrototypeContract; +} + +function analyzedIr(): unknown { + return JSON.parse( + execFileSync( + PYTHON ?? 'python3', + [ + '-c', + "from tywrap_ir.ir import emit_ir_json; print(emit_ir_json('value_contract_exact_integer', pretty=False))", + ], + { env: pythonEnvironment, encoding: 'utf8' } + ) + ) as unknown; +} + +function compileInteger(ir: unknown, exact: boolean, bound = false): CompiledContract { + const validated = validateIrContract(ir, 'analyzed exact integer IR'); + expect(validated.ok).toBe(true); + if (!validated.ok) throw new Error('Exact integer IR is invalid'); + const module = transformIrToTsModel(validated.contract); + const generator = new CodeGenerator(); + return compileContract(validated.contract, { + module, + generator: bound + ? { + generateModuleDefinition(model: PythonModule, annotatedJSDoc = false) { + return generator.generateModuleBindingTemplate(model, annotatedJSDoc); + }, + } + : generator, + conversion: exact ? EXACT_INTEGER_VALUE_CONVERSION : DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES.map(capability => + capability.name === 'exact-integer-adapter' ? { ...capability, available: exact } : capability + ), + }); +} + +function descriptorFrom(compiled: CompiledContract, name: string): ExactInvocationDescriptor { + const callable = compiled.callables.find(item => item.name === name); + const functionModel = compiled.module.functions.find(item => item.name === name); + if (!callable || !functionModel || callable.result.resolution.status !== 'supported') { + throw new Error('Exact callable result is unresolved'); + } + const fields: Record = {}; + for (const [index, parameter] of functionModel.parameters.entries()) { + const resolution = callable.parameters[index]?.resolution; + if (!resolution || resolution.status !== 'supported') { + throw new Error(`Exact parameter ${parameter.name} is unresolved`); + } + fields[parameter.name] = toExactPrototypeContract(resolution.value); + } + return { + requiredCapability: 'exactIntegerDecimalV2', + valuePolicy: { integer: 'bigint-v2' }, + args: { kind: 'record', fields }, + result: toExactPrototypeContract(callable.result.resolution.value), + }; +} + +describe.skipIf(!PYTHON_AVAILABLE || !existsSync(fixturePath) || !existsSync(pythonAdapter))( + 'generated exact integer proof', + () => { + it('keeps default numeric types and fails closed without exact adapter capability', () => { + const ir = analyzedIr(); + const ordinary = compileInteger(ir, false); + expect(ordinary.generated.declaration).toContain('value: number'); + expect(ordinary.generated.declaration).toContain('nested: number[]'); + expect(ordinary.generated.declaration).toContain('Promise'); + expect(ordinary.generated.declaration).toContain('Promise'); + + const validated = validateIrContract(ir, 'exact integer capability control'); + expect(validated.ok).toBe(true); + if (!validated.ok) throw new Error('Exact integer IR is invalid'); + const module = transformIrToTsModel(validated.contract); + expect(() => + compileContract(validated.contract, { + module, + generator: new CodeGenerator(), + conversion: EXACT_INTEGER_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES, + }) + ).toThrow(/exact-integer-adapter is unavailable/); + }); + + it('executes a bound bigint wrapper with pre-send capability checks', async () => { + const compiled = compileInteger(analyzedIr(), true, true); + const descriptors = { + combine_exact: descriptorFrom(compiled, 'combine_exact'), + echo_exact: descriptorFrom(compiled, 'echo_exact'), + }; + for (const callable of compiled.callables) { + expect(callable.requiredCapabilities).toContain('exact-integer-adapter'); + } + expect(compiled.generated.declaration).toContain('value: bigint'); + expect(compiled.generated.declaration).toContain('nested: bigint[]'); + expect(compiled.generated.declaration).toContain('flag: boolean'); + expect(compiled.generated.declaration).toContain('ratio: number'); + expect(compiled.generated.declaration).toContain('Promise'); + expect(compiled.generated.declaration).toContain('Promise'); + expect(compiled.generated.typescript).toContain('"kind":"primitive","type":"bigint"'); + expect(compiled.generated.typescript).toContain('__tywrapRuntimeProvider().call'); + + const temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-integer-')); + try { + const outputPath = join(temporary, 'value_contract_exact_integer.generated.mjs'); + const declarationPath = join(temporary, 'value_contract_exact_integer.generated.d.ts'); + const consumerPath = join(temporary, 'consumer.ts'); + const binding = ` +import { getRuntimeBridge } from 'tywrap/runtime'; +const __tywrapExactDescriptors = ${JSON.stringify(descriptors)} as Record; +type PolicyCall = ( + module: string, + functionName: string, + args: unknown[], + kwargs: Record | undefined, + validate: ((result: T) => void) | undefined, + descriptor: unknown +) => Promise; +function __tywrapRuntimeProvider() { + const bridge = getRuntimeBridge() as ReturnType & { + meta?: { valueCapabilities?: unknown }; + callWithValuePolicy?: PolicyCall; + }; + const capabilities = bridge.meta?.valueCapabilities; + if (!Array.isArray(capabilities) || !capabilities.includes('exactIntegerDecimalV2')) { + throw new Error('bridge lacks exactIntegerDecimalV2 capability'); + } + if (typeof bridge.callWithValuePolicy !== 'function') { + throw new Error('bridge lacks the exact integer value-policy adapter'); + } + return { + call( + module: string, + functionName: string, + args: unknown[], + kwargs?: Record, + validate?: (result: T) => void + ): Promise { + const descriptor = __tywrapExactDescriptors[functionName]; + if (!descriptor) { + throw new Error('exact integer descriptor is missing'); + } + return bridge.callWithValuePolicy!( + module, functionName, args, kwargs, validate, descriptor + ); + }, + }; +} +`; + const javascript = ts.transpileModule(compiled.generated.typescript + binding, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(outputPath, javascript, 'utf8'); + await writeFile(declarationPath, compiled.generated.declaration, 'utf8'); + await writeFile( + consumerPath, + `import { combineExact, echoExact } from './value_contract_exact_integer.generated.js'; +const result: Promise = combineExact(1n, [2n], true, 1.5); +const nested: Promise = echoExact(1n, [2n]); +result.then(value => { + const valid: bigint = value; + // @ts-expect-error Exact result is bigint. + const wrong: number = value; + return valid + BigInt(wrong); +}); +nested.then(rows => { + const valid: bigint = rows[0]![0]!; + // @ts-expect-error Nested exact result is bigint. + const wrong: number = rows[0]![0]!; + return valid + BigInt(wrong); +}); +// @ts-expect-error Exact input is bigint. +combineExact(1, [2n], true, 1.5); +// @ts-expect-error Nested exact input is bigint[]. +combineExact(1n, [2], true, 1.5); +// @ts-expect-error Nested exact input is bigint[]. +echoExact(1n, [2]);`, + 'utf8' + ); + const program = ts.createProgram([consumerPath], { + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + target: ts.ScriptTarget.ES2022, + strict: true, + noEmit: true, + skipLibCheck: true, + types: [], + }); + expect( + ts + .getPreEmitDiagnostics(program) + .map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')) + ).toEqual([]); + + let sent = 0; + let responseOverride: unknown; + let maxRequestBytes = 10 * 1024 * 1024; + const bridge = { + meta: { valueCapabilities: ['exactIntegerDecimalV2'] }, + async call(): Promise { + throw new Error('the exact wrapper must use its policy adapter'); + }, + async callWithValuePolicy( + moduleName: string, + functionName: string, + args: unknown[], + _kwargs?: Record, + validate?: (result: T) => void, + invocation?: ExactInvocationDescriptor + ): Promise { + expect(moduleName).toBe('value_contract_exact_integer'); + expect(['combine_exact', 'echo_exact']).toContain(functionName); + expect(invocation).toEqual(descriptors[functionName as keyof typeof descriptors]); + if (!invocation || invocation.args.kind !== 'record') { + throw new Error('Exact invocation descriptor is missing'); + } + const names = Object.keys(invocation.args.fields); + const input = Object.fromEntries(names.map((name, index) => [name, args[index]])); + const encoded = encodeExactRequest(input, invocation.args) as Record; + const request = { + module: moduleName, + functionName, + params: { + valuePolicy: invocation.valuePolicy, + args: names.map(name => encoded[name]), + }, + }; + const raw = JSON.stringify(request); + if (new TextEncoder().encode(raw).length > maxRequestBytes) { + throw new Error('exact request exceeds byte limit'); + } + sent += 1; + const response = JSON.parse( + execFileSync( + PYTHON ?? 'python3', + [ + pythonAdapter, + JSON.stringify(invocation.args), + JSON.stringify(this.meta), + functionName, + ], + { input: raw, env: pythonEnvironment, encoding: 'utf8', maxBuffer: 1024 * 1024 } + ) + ) as unknown; + const decoded = decodeExactResponse( + responseOverride === undefined ? response : responseOverride, + invocation.result + ); + validate?.(decoded as T); + return decoded as T; + }, + async dispose(): Promise {}, + }; + setRuntimeBridge(bridge); + const generated = (await import(pathToFileURL(outputPath).href)) as { + combineExact: ( + value: bigint, + nested: bigint[], + flag: boolean, + ratio: number + ) => Promise; + echoExact: (value: bigint, nested: bigint[]) => Promise; + }; + + const positive = 2n ** 80n + 1n; + const negative = -(2n ** 130n + 7n); + await expect(generated.combineExact(positive, [7n, negative], true, 1.5)).resolves.toBe( + positive + 7n + negative + ); + await expect(generated.combineExact(7n, [2n], true, 0)).resolves.toBe(9n); + await expect(generated.combineExact(7n, [2n], true, -0)).resolves.toBe(-9n); + await expect(generated.combineExact(7n, [2n], false, 1.5)).resolves.toBe(-9n); + await expect(generated.echoExact(positive, [negative, 7n])).resolves.toEqual([ + [positive], + [negative, 7n], + [-positive], + ]); + + const beforeOversize = sent; + maxRequestBytes = 100; + await expect(generated.echoExact(7n, [2n])).rejects.toThrow( + /exact request exceeds byte limit/ + ); + expect(sent).toBe(beforeOversize); + maxRequestBytes = 10 * 1024 * 1024; + + const beforeMissing = sent; + bridge.meta = { valueCapabilities: [] }; + await expect(generated.combineExact(7n, [2n], true, 1.5)).rejects.toThrow( + /bridge lacks exactIntegerDecimalV2 capability/ + ); + expect(sent).toBe(beforeMissing); + bridge.meta = { valueCapabilities: ['exactIntegerDecimalV2'] }; + responseOverride = { + __tywrap__: 'integer', + codecVersion: 1, + encoding: 'decimal', + value: '9', + }; + await expect(generated.combineExact(7n, [2n], true, 1.5)).rejects.toThrow( + /invalid integer envelope/ + ); + responseOverride = 9; + await expect(generated.combineExact(7n, [2n], true, 1.5)).rejects.toThrow( + /expected integer envelope/ + ); + responseOverride = [ + [{ __tywrap__: 'integer', codecVersion: 2, encoding: 'decimal', value: '7' }], + [{ __tywrap__: 'integer', codecVersion: 1, encoding: 'decimal', value: '2' }], + ]; + await expect(generated.echoExact(7n, [2n])).rejects.toThrow(/invalid integer envelope/); + + const bypassBridge = { + meta: { valueCapabilities: ['exactIntegerDecimalV2'] }, + async call(): Promise { + throw new Error('ordinary call must not run'); + }, + async callWithValuePolicy( + _module: string, + functionName: string, + _args: unknown[], + _kwargs?: Record, + validate?: (result: T) => void + ): Promise { + const wrong = + functionName === 'echo_exact' ? ([[7n], [2, 3n]] as unknown as T) : (9 as T); + validate?.(wrong); + return wrong; + }, + async dispose(): Promise {}, + }; + setRuntimeBridge(bypassBridge); + await expect(generated.combineExact(7n, [2n], true, 1.5)).rejects.toThrow( + BridgeValidationError + ); + await expect(generated.echoExact(7n, [2n])).rejects.toThrow(BridgeValidationError); + + const ordinary = compileInteger(analyzedIr(), false); + const ordinaryPath = join(temporary, 'value_contract_integer_default.generated.mjs'); + await writeFile( + ordinaryPath, + ts.transpileModule(ordinary.generated.typescript, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText, + 'utf8' + ); + let ordinaryCalls = 0; + let exactCalls = 0; + const compatibleBridge = { + async call(): Promise { + ordinaryCalls += 1; + return 9 as T; + }, + async callWithValuePolicy(): Promise { + exactCalls += 1; + throw new Error('default calls must not select the exact policy'); + }, + async dispose(): Promise {}, + }; + setRuntimeBridge(compatibleBridge); + const defaultGenerated = (await import(pathToFileURL(ordinaryPath).href)) as { + combineExact: ( + value: number, + nested: number[], + flag: boolean, + ratio: number + ) => Promise; + }; + await expect(defaultGenerated.combineExact(7, [2], true, 1.5)).resolves.toBe(9); + expect(ordinaryCalls).toBe(1); + expect(exactCalls).toBe(0); + + const serverGuard = spawnSync( + PYTHON ?? 'python3', + [ + pythonAdapter, + JSON.stringify(descriptors.echo_exact.args), + JSON.stringify(bridge.meta), + 'echo_exact', + ], + { + input: Buffer.alloc(10 * 1024 * 1024 + 1, 0x20), + env: pythonEnvironment, + encoding: 'utf8', + maxBuffer: 1024 * 1024, + } + ); + expect(serverGuard.status).not.toBe(0); + expect(serverGuard.stderr).toContain('input payload exceeds byte limit'); + } finally { + clearRuntimeBridge(); + await rm(temporary, { recursive: true, force: true }); + } + }); + } +); diff --git a/test/value_extensions_generated_point.test.ts b/test/value_extensions_generated_point.test.ts new file mode 100644 index 00000000..6920ef2d --- /dev/null +++ b/test/value_extensions_generated_point.test.ts @@ -0,0 +1,364 @@ +import { execFileSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { delimiter, join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import ts from 'typescript'; +import { describe, expect, it } from 'vitest'; +import { + compileContract, + DEFAULT_CALLABLE_CAPABILITIES, + DEFAULT_VALUE_CONVERSION, + type ValueConversionDescription, +} from '../src/core/callable-compiler.js'; +import { CodeGenerator } from '../src/core/generator.js'; +import { validateIrContract } from '../src/core/ir-contract.js'; +import { transformIrToTsModel } from '../src/core/ir-model.js'; +import { + VALUE_CONTRACT_REVISION, + type ValueContractField, +} from '../src/contracts/value-contract.js'; +import { BridgeValidationError } from '../src/runtime/errors.js'; +import { clearRuntimeBridge, setRuntimeBridge } from 'tywrap/runtime'; +import type { PythonModule } from '../src/types/index.js'; +import { PYTHON, PYTHON_AVAILABLE } from './helpers/python-probe.js'; +import { + decodeExactResponse, + requireCapability, + validateDataclassOrigin, + type PrototypeContract, +} from './prototypes/value_extensions.js'; + +const pythonScript = join(process.cwd(), 'test', 'prototypes', 'value_extensions.py'); +const fixtureDir = join(process.cwd(), 'test', 'fixtures', 'python'); +const fixturePath = join(fixtureDir, 'value_contract_point.py'); +const pythonEnvironment = { + ...process.env, + PYTHONPATH: [ + fixtureDir, + join(process.cwd(), 'tywrap_ir'), + join(process.cwd(), 'test', 'prototypes'), + process.env.PYTHONPATH, + ] + .filter(Boolean) + .join(delimiter), +}; + +interface PointInvocationDescriptor { + requiredCapability: 'dataclassFieldsV2'; + valuePolicy: { dataclass: 'fields-v2' }; + result: PrototypeContract; +} + +function analyzedPointIr(): unknown { + return JSON.parse( + execFileSync( + PYTHON ?? 'python3', + [ + '-c', + "from tywrap_ir.ir import emit_ir_json; print(emit_ir_json('value_contract_point', pretty=False))", + ], + { env: pythonEnvironment, encoding: 'utf8' } + ) + ) as unknown; +} + +function pointConversion(module: PythonModule): ValueConversionDescription { + const point = module.classes.find(cls => cls.name === 'Point' && cls.kind === 'dataclass'); + if (!point) throw new Error('Analyzed Point dataclass is missing'); + return { + revision: VALUE_CONTRACT_REVISION, + resolve(request) { + if ( + request.direction !== 'output' || + request.logicalType.kind !== 'custom' || + request.logicalType.name.split('.').at(-1) !== point.name + ) { + return DEFAULT_VALUE_CONVERSION.resolve(request); + } + const fields: ValueContractField[] = []; + for (const property of point.properties) { + const resolved = DEFAULT_VALUE_CONVERSION.resolve({ + ...request, + logicalType: property.type, + path: `${request.path}.${property.name}`, + }); + if (resolved.status !== 'supported') { + return { + status: 'unsupported', + reason: `No value contract for Point.${property.name}`, + guidance: 'Use a supported dataclass field annotation.', + }; + } + fields.push({ name: property.name, value: resolved.value, required: true }); + } + return { + status: 'supported', + value: { kind: 'record', wire: 'json', decodedAs: 'object', fields }, + }; + }, + }; +} + +function compilePoint(sourceIr: unknown, useAdapter: boolean, enableAdapter: boolean) { + const validated = validateIrContract(sourceIr, 'analyzed Point IR'); + expect(validated.ok).toBe(true); + if (!validated.ok) throw new Error('Analyzed Point IR is invalid'); + const canonical = transformIrToTsModel(validated.contract); + const module = { + ...canonical, + functions: canonical.functions.filter(func => func.name === 'make_point'), + classes: canonical.classes.filter(cls => cls.name === 'Point'), + }; + const compiled = compileContract(validated.contract, { + module, + generator: new CodeGenerator(), + conversion: useAdapter ? pointConversion(module) : DEFAULT_VALUE_CONVERSION, + capabilities: DEFAULT_CALLABLE_CAPABILITIES.map(capability => + capability.name === 'dataclass-adapter' + ? { ...capability, available: enableAdapter } + : capability + ), + }); + return { compiled, ir: validated.contract }; +} + +function pythonPoint(): unknown { + return JSON.parse( + execFileSync( + PYTHON ?? 'python3', + [ + '-c', + "import json; from value_contract_point import Point, make_point; from value_extensions import encode_dataclass; print(json.dumps(encode_dataclass(make_point(), Point), separators=(',', ':')))", + ], + { + env: pythonEnvironment, + encoding: 'utf8', + } + ) + ) as unknown; +} + +function pointContractFrom(result: ReturnType): PrototypeContract { + const point = result.ir.classes.find(cls => cls.name === 'Point'); + const resolution = result.compiled.callables.find(item => item.name === 'make_point')?.result + .resolution; + if ( + !point || + !resolution || + resolution.status !== 'supported' || + resolution.value.kind !== 'record' + ) { + throw new Error('Analyzed Point output did not resolve to a record'); + } + const fields: Record = {}; + for (const field of resolution.value.fields) { + if (field.value.kind !== 'integer' || field.value.constraint !== 'safe-integer') { + throw new Error(`Unsupported Point field ${field.name}`); + } + fields[field.name] = { kind: 'safe-integer' }; + } + return { kind: 'dataclass', typeId: point.qualname, fields }; +} + +describe.skipIf(!PYTHON_AVAILABLE || !existsSync(pythonScript) || !existsSync(fixturePath))( + 'generated Point output prototype', + () => { + it('keeps defaults, missing capability, and unsupported fields unresolved', () => { + const pointIr = analyzedPointIr(); + const defaultResult = compilePoint(pointIr, false, false).compiled; + expect(defaultResult.callables[0]?.result.resolution.status).toBe('unsupported'); + expect(defaultResult.generated.declaration).toContain('Promise'); + + const missingCapability = compilePoint(pointIr, true, false).compiled; + expect(missingCapability.callables[0]?.result.resolution.status).toBe('unsupported'); + + const unsupportedIr = structuredClone(pointIr) as { + classes: Array<{ name: string; fields: Array<{ annotation: string }> }>; + }; + const point = unsupportedIr.classes.find(cls => cls.name === 'Point'); + if (!point) throw new Error('Analyzed Point dataclass is missing'); + point.fields[0]!.annotation = 'object'; + const unsupported = compilePoint(unsupportedIr, true, true).compiled; + expect(unsupported.callables[0]?.result.resolution.status).toBe('unsupported'); + expect(unsupported.generated.declaration).toContain('Promise'); + }); + + it('executes a generated Promise through the Python prototype adapter', async () => { + const pointIr = analyzedPointIr(); + const result = compilePoint(pointIr, true, true); + const { compiled } = result; + const pointContract = pointContractFrom(result); + const descriptor: PointInvocationDescriptor = { + requiredCapability: 'dataclassFieldsV2', + valuePolicy: { dataclass: 'fields-v2' }, + result: pointContract, + }; + expect(compiled.diagnostics.filter(item => item.severity === 'error')).toEqual([]); + expect(compiled.callables[0]?.requiredCapabilities).toContain('dataclass-adapter'); + expect(compiled.generated.declaration).toContain('makePoint(): Promise'); + expect(compiled.generated.declaration).toContain( + 'export type Point = { x: number; y: number; }' + ); + expect(result.ir.classes.find(cls => cls.name === 'Point')?.fields[1]?.default).toBe(true); + expect(compiled.generated.typescript).toContain('"constraint":"safe-integer"'); + const bound = new CodeGenerator().generateModuleBindingTemplate(compiled.module); + expect(bound.declaration).toBe(compiled.generated.declaration); + expect(bound.typescript).toContain('__tywrapRuntimeProvider().call'); + expect(bound.typescript).not.toContain('getRuntimeBridge().call'); + + const temporary = await mkdtemp(join(process.cwd(), 'test', '.tywrap-point-')); + try { + const outputPath = join(temporary, 'value_contract_point.generated.mjs'); + const declarationPath = join(temporary, 'value_contract_point.generated.d.ts'); + const consumerPath = join(temporary, 'consumer.ts'); + const binding = ` +import { getRuntimeBridge } from 'tywrap/runtime'; +type PolicyCall = ( + module: string, + functionName: string, + args: unknown[], + kwargs: Record | undefined, + validate: ((result: T) => void) | undefined, + descriptor: unknown +) => Promise; +function __tywrapRuntimeProvider() { + const bridge = getRuntimeBridge() as ReturnType & { + callWithValuePolicy?: PolicyCall; + }; + if (typeof bridge.callWithValuePolicy !== 'function') { + throw new Error('bridge lacks the Point value-policy adapter'); + } + return { + call( + module: string, + functionName: string, + args: unknown[], + kwargs?: Record, + validate?: (result: T) => void + ): Promise { + return bridge.callWithValuePolicy!( + module, functionName, args, kwargs, validate, ${JSON.stringify(descriptor)} + ); + }, + }; +} +`; + const javascript = ts.transpileModule(bound.typescript + binding, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText; + await writeFile(outputPath, javascript, 'utf8'); + await writeFile(declarationPath, compiled.generated.declaration, 'utf8'); + await writeFile( + consumerPath, + `import { makePoint, type Point } from './value_contract_point.generated.js'; +const result: Promise = makePoint(); +result.then(point => { + const x: number = point.x; + const y: number = point.y; + // @ts-expect-error Point.x is a number. + const wrong: string = point.x; + // @ts-expect-error Point has no z field. + point.z; + return x + y + wrong.length; +});`, + 'utf8' + ); + const program = ts.createProgram([consumerPath], { + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + target: ts.ScriptTarget.ES2022, + strict: true, + noEmit: true, + skipLibCheck: true, + types: [], + }); + expect( + ts + .getPreEmitDiagnostics(program) + .map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')) + ).toEqual([]); + + let wire: unknown = pythonPoint(); + let bridgeMeta: unknown = { valueCapabilities: ['dataclassFieldsV2'] }; + const adapterBridge = { + async call(): Promise { + throw new Error('the bound Point wrapper must use the policy adapter'); + }, + async callWithValuePolicy( + moduleName: string, + functionName: string, + _args: unknown[], + _kwargs?: Record, + validate?: (result: T) => void, + invocation?: PointInvocationDescriptor + ): Promise { + expect([moduleName, functionName]).toEqual(['value_contract_point', 'make_point']); + expect(invocation).toEqual(descriptor); + if (!invocation) throw new Error('Point invocation descriptor is missing'); + requireCapability( + bridgeMeta, + invocation.requiredCapability, + invocation.valuePolicy.dataclass + ); + const decoded = decodeExactResponse(wire, invocation.result); + validateDataclassOrigin(decoded, invocation.result); + validate?.(decoded as T); + return decoded as T; + }, + async dispose(): Promise {}, + }; + setRuntimeBridge(adapterBridge); + const generated = (await import(pathToFileURL(outputPath).href)) as { + makePoint: () => Promise<{ x: number; y: number }>; + }; + + await expect(generated.makePoint()).resolves.toEqual({ x: 1, y: 2 }); + setRuntimeBridge({ + async call(): Promise { + throw new Error('ordinary bridge call must not run'); + }, + async dispose(): Promise {}, + }); + await expect(generated.makePoint()).rejects.toThrow(/lacks the Point value-policy adapter/); + setRuntimeBridge(adapterBridge); + bridgeMeta = {}; + await expect(generated.makePoint()).rejects.toThrow(/bridge lacks dataclassFieldsV2/); + bridgeMeta = { valueCapabilities: ['dataclassFieldsV2'] }; + const valid = pythonPoint() as { fields: Record }; + for (const [bad, error] of [ + [{ ...valid, fields: { x: 1 } }, /fields differ at result\.fields/], + [{ ...valid, fields: { x: 1, y: 2, z: 3 } }, /fields differ at result\.fields/], + [{ ...valid, fields: { x: '1', y: 2 } }, /expected safe integer at result\.fields\.x/], + [{ ...valid, type: 'other.Point' }, /invalid dataclass identity at result/], + [{ x: 1, y: 2 }, /fields differ at result/], + ] as const) { + wire = bad; + await expect(generated.makePoint()).rejects.toThrow(error); + } + + setRuntimeBridge({ + async call(): Promise { + throw new Error('ordinary bridge call must not run'); + }, + async callWithValuePolicy( + _module: string, + _functionName: string, + _args: unknown[], + _kwargs?: Record, + validate?: (result: T) => void + ): Promise { + const wrong = { x: '1', y: 2 } as unknown as T; + validate?.(wrong); + return wrong; + }, + async dispose(): Promise {}, + }); + await expect(generated.makePoint()).rejects.toThrow(BridgeValidationError); + } finally { + clearRuntimeBridge(); + await rm(temporary, { recursive: true, force: true }); + } + }); + } +); diff --git a/test/value_extensions_prototype.test.ts b/test/value_extensions_prototype.test.ts new file mode 100644 index 00000000..fb55abb7 --- /dev/null +++ b/test/value_extensions_prototype.test.ts @@ -0,0 +1,270 @@ +import { execFileSync, spawnSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { PYTHON, PYTHON_AVAILABLE } from './helpers/python-probe.js'; +import { + decodeExactResponse, + encodeExactRequest, + requireCapability, + validateDataclassOrigin, + type PrototypeContract, +} from './prototypes/value_extensions.js'; + +const pythonScript = join(process.cwd(), 'test', 'prototypes', 'value_extensions.py'); +const pythonPath = PYTHON ?? 'python3'; + +function pythonAction(action: string, input: string): unknown { + return JSON.parse( + execFileSync(pythonPath, [pythonScript, action], { + input, + encoding: 'utf8', + maxBuffer: 1024 * 1024, + }) + ) as unknown; +} + +const integerContract: PrototypeContract = { + kind: 'record', + fields: { + positive: { kind: 'array', item: { kind: 'integer' } }, + negative: { kind: 'record', fields: { value: { kind: 'integer' } } }, + safe: { kind: 'integer' }, + flag: { kind: 'boolean' }, + whole: { kind: 'float' }, + fraction: { kind: 'float' }, + negativeZero: { kind: 'float' }, + mixed: { + kind: 'array', + item: { + kind: 'record', + fields: { + quantity: { kind: 'integer' }, + ratio: { kind: 'float' }, + flag: { kind: 'boolean' }, + }, + }, + }, + }, +}; + +describe.skipIf(!PYTHON_AVAILABLE || !existsSync(pythonScript))( + 'exact integer cross-language prototype', + () => { + it('round-trips nested positive and negative values beyond int64 in both directions', () => { + const positive = 2n ** 80n + 1n; + const negative = -(2n ** 130n + 7n); + const value = { + positive: [positive], + negative: { value: negative }, + safe: 7n, + flag: true, + whole: 1, + fraction: 1.5, + negativeZero: -0, + mixed: [{ quantity: -9n, ratio: 2, flag: false }], + }; + + const pythonWire = pythonAction( + 'encode-integer', + `{"positive":[${positive}],"negative":{"value":${negative}},"safe":7,"flag":true,"whole":1.0,"fraction":1.5,"negativeZero":-0.0,"mixed":[{"quantity":-9,"ratio":2.0,"flag":false}]}` + ); + expect(decodeExactResponse(pythonWire, integerContract)).toEqual(value); + + requireCapability( + { valueCapabilities: ['exactIntegerDecimalV2'] }, + 'exactIntegerDecimalV2', + 'bigint-v2' + ); + const request = encodeExactRequest(value, integerContract); + expect((request as { negativeZero: unknown }).negativeZero).toEqual({ + __tywrap__: 'float', + codecVersion: 2, + encoding: 'negative-zero', + }); + const response = pythonAction( + 'roundtrip-integer', + JSON.stringify({ + meta: { valueCapabilities: ['exactIntegerDecimalV2'] }, + policy: 'bigint-v2', + value: request, + }) + ); + expect(decodeExactResponse(response, integerContract)).toEqual(value); + expect(Object.is((response as { negativeZero: number }).negativeZero, -0)).toBe(true); + }); + } +); + +describe('exact integer rejection prototype', () => { + const integer: PrototypeContract = { kind: 'integer' }; + + it('rejects an old bridge, a number under bigint typing, and a version 1 tag', () => { + expect(() => requireCapability({}, 'exactIntegerDecimalV2', 'bigint-v2')).toThrow( + /bridge lacks/ + ); + expect(() => encodeExactRequest(42, integer)).toThrow(/expected bigint at args/); + expect(() => + decodeExactResponse( + { __tywrap__: 'integer', codecVersion: 1, encoding: 'decimal', value: '42' }, + integer + ) + ).toThrow(/invalid integer envelope/); + }); + + it.each(['-0', '+1', '01', '-01', '1.0', '1e2', ' 1', '١'])( + 'rejects noncanonical decimal %s', + decimal => { + expect(() => + decodeExactResponse( + { __tywrap__: 'integer', codecVersion: 2, encoding: 'decimal', value: decimal }, + integer + ) + ).toThrow(/noncanonical integer decimal/); + } + ); + + it('enforces digit and payload limits', () => { + const max = BigInt('9'.repeat(4096)); + expect(decodeExactResponse(encodeExactRequest(max, integer), integer)).toBe(max); + expect(() => encodeExactRequest(BigInt('9'.repeat(4097)), integer)).toThrow(/4096 digits/); + expect(() => encodeExactRequest(1n, integer, 20)).toThrow(/payload exceeds 20 bytes/); + }); + + it('counts compact UTF-8 JSON bytes for Unicode strings and nested records', () => { + const text: PrototypeContract = { kind: 'string' }; + expect(encodeExactRequest('é', text, 4)).toBe('é'); + expect(() => encodeExactRequest('é', text, 3)).toThrow(/payload exceeds 3 bytes/); + + const nested = { café: ['🍵', 'é'] }; + const nestedContract: PrototypeContract = { + kind: 'record', + fields: { café: { kind: 'array', item: text } }, + }; + const limit = new TextEncoder().encode('{"café":["🍵","é"]}').length; + expect(encodeExactRequest(nested, nestedContract, limit)).toEqual(nested); + expect(() => encodeExactRequest(nested, nestedContract, limit - 1)).toThrow(/payload exceeds/); + expect(() => encodeExactRequest('\ud800', text)).toThrow(/unpaired Unicode surrogate/); + }); + + it('rejects a record key reserved for envelopes', () => { + const record: PrototypeContract = { + kind: 'record', + fields: { __tywrap__: { kind: 'string' } }, + }; + expect(() => encodeExactRequest({ __tywrap__: 'ordinary' }, record)).toThrow( + /reserved record key/ + ); + }); + + it('rejects malformed negative-zero envelopes', () => { + const float: PrototypeContract = { kind: 'float' }; + expect(() => + decodeExactResponse( + { __tywrap__: 'float', codecVersion: 1, encoding: 'negative-zero' }, + float + ) + ).toThrow(/invalid float envelope/); + }); +}); + +describe.skipIf(!PYTHON_AVAILABLE || !existsSync(pythonScript))( + 'cross-language version and Unicode policy', + () => { + it.each([ + ['2', true], + ['2.0', true], + ['2e0', true], + ['true', false], + ['"2"', false], + ['2.5', false], + ['null', false], + ] as const)('agrees on integer envelope version %s', (version, accepted) => { + const raw = `{"meta":{"valueCapabilities":["exactIntegerDecimalV2"]},"policy":"bigint-v2","value":{"__tywrap__":"integer","codecVersion":${version},"encoding":"decimal","value":"7"}}`; + const request = JSON.parse(raw) as { value: unknown }; + if (accepted) { + expect(decodeExactResponse(request.value, { kind: 'integer' })).toBe(7n); + } else { + expect(() => decodeExactResponse(request.value, { kind: 'integer' })).toThrow(); + } + const python = spawnSync(pythonPath, [pythonScript, 'roundtrip-single-integer'], { + input: raw, + encoding: 'utf8', + }); + expect(python.status === 0).toBe(accepted); + if (accepted) { + expect(JSON.parse(python.stdout)).toEqual({ + __tywrap__: 'integer', + codecVersion: 2, + encoding: 'decimal', + value: '7', + }); + } + }); + + it('agrees on nested Unicode and rejects unpaired surrogates', () => { + const nested = { café: ['🍵', 'é'] }; + expect(pythonAction('encode-integer', JSON.stringify(nested))).toEqual(nested); + const encoded = spawnSync(pythonPath, [pythonScript, 'encode-integer'], { + input: JSON.stringify(nested), + encoding: 'utf8', + }); + expect(encoded.status).toBe(0); + expect(encoded.stdout.trim()).toBe(JSON.stringify(nested)); + const wire = Buffer.from(JSON.stringify(nested), 'utf8'); + const exact = spawnSync(pythonPath, [pythonScript, 'encode-integer-limited'], { + input: JSON.stringify({ value: nested, limit: wire.length }), + }); + expect(exact.status).toBe(0); + expect(exact.stdout).toEqual(Buffer.concat([wire, Buffer.from('\n')])); + expect(exact.stdout.subarray(0, -1).length).toBe(wire.length); + const tooSmall = spawnSync(pythonPath, [pythonScript, 'encode-integer-limited'], { + input: JSON.stringify({ value: nested, limit: wire.length - 1 }), + }); + expect(tooSmall.status).not.toBe(0); + + const short = spawnSync(pythonPath, [pythonScript, 'encode-integer-limited'], { + input: JSON.stringify({ value: 'é', limit: 4 }), + }); + expect(short.stdout).toEqual(Buffer.from('"é"\n', 'utf8')); + expect(short.stdout.subarray(0, -1).length).toBe(4); + const bad = spawnSync(pythonPath, [pythonScript, 'encode-integer'], { + input: JSON.stringify('\ud800'), + encoding: 'utf8', + }); + expect(bad.status).not.toBe(0); + expect(bad.stderr).toContain('PrototypeError'); + }); + } +); + +describe.skipIf(!PYTHON_AVAILABLE || !existsSync(pythonScript))( + 'dataclass output prototype', + () => { + const point: PrototypeContract = { + kind: 'dataclass', + typeId: '__main__.Point', + fields: { x: { kind: 'safe-integer' }, y: { kind: 'safe-integer' } }, + }; + + it('decodes Point and preserves verified origin', () => { + expect(() => encodeExactRequest({ x: 1, y: 2 }, point)).toThrow( + /dataclass inputs are unsupported at args/ + ); + const wire = pythonAction('encode-point', JSON.stringify({ x: 1, y: 2 })); + const decoded = decodeExactResponse(wire, point); + expect(decoded).toEqual({ x: 1, y: 2 }); + expect(() => validateDataclassOrigin(decoded, point)).not.toThrow(); + expect(() => validateDataclassOrigin({ x: 1, y: 2 }, point)).toThrow(/lacks verified/); + expect(() => + decodeExactResponse({ ...(wire as object), type: 'other.Point' }, point) + ).toThrow(/invalid dataclass identity/); + expect(() => decodeExactResponse({ ...(wire as object), fields: { x: 1 } }, point)).toThrow( + /fields differ/ + ); + expect(() => + decodeExactResponse({ ...(wire as object), fields: { x: '1', y: 2 } }, point) + ).toThrow(/expected safe integer/); + }); + } +); diff --git a/tywrap_ir/tywrap_ir/ir.py b/tywrap_ir/tywrap_ir/ir.py index 95c4f5bc..d8198719 100644 --- a/tywrap_ir/tywrap_ir/ir.py +++ b/tywrap_ir/tywrap_ir/ir.py @@ -493,11 +493,13 @@ def _extract_function( # Async generators must be marked as generators so callers can distinguish # them from plain coroutines. is_generator = inspect.isgeneratorfunction(obj) or inspect.isasyncgenfunction(obj) + overloads, overload_annotations = _extract_overloads(obj) type_params = ( _collect_scoped_type_params( obj, *annotations_for_params, returns, + *overload_annotations, inherited_type_params=inherited_type_params, ) if include_type_params @@ -514,7 +516,7 @@ def _extract_function( is_generator=is_generator, type_params=type_params, method_kind=method_kind, - overloads=_extract_overloads(obj), + overloads=overloads, ) @@ -525,8 +527,8 @@ def _extract_function( _overload_warning_recorded = False -def _extract_overloads(obj: Any) -> List[IROverload]: - """Capture @typing.overload signatures for ``obj`` (Python 3.11+). +def _extract_overloads(obj: Any) -> tuple[List[IROverload], List[Any]]: + """Capture overload signatures and their raw annotations (Python 3.11+). On interpreters without ``typing.get_overloads`` (3.10 and earlier) this degrades to an empty list and records a single structured IR warning @@ -541,14 +543,15 @@ def _extract_overloads(obj: Any) -> List[IROverload]: "typing.get_overloads is unavailable (Python < 3.11); " "@overload signatures will not be captured in the IR." ) - return [] + return [], [] try: registered = get_overloads(obj) except Exception: - return [] + return [], [] out: List[IROverload] = [] + annotations: List[Any] = [] for ov in registered or (): try: sig = inspect.signature(ov) @@ -564,6 +567,7 @@ def _extract_overloads(obj: Any) -> List[IROverload]: params: List[IRParam] = [] for pname, p in sig.parameters.items(): ann = hints.get(pname, p.annotation) + annotations.append(ann) params.append( IRParam( name=pname, @@ -573,8 +577,9 @@ def _extract_overloads(obj: Any) -> List[IROverload]: ) ) ret = hints.get("return", sig.return_annotation) + annotations.append(ret) out.append(IROverload(parameters=params, returns=_stringify_annotation(ret))) - return out + return out, annotations def _accessor_return_annotation(getter: Any) -> Optional[str]: diff --git a/vitest.isolated-consumer.config.ts b/vitest.isolated-consumer.config.ts new file mode 100644 index 00000000..fe17217a --- /dev/null +++ b/vitest.isolated-consumer.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['test/isolated_consumer.conformance.ts'], + testTimeout: 300_000, + }, +}); diff --git a/vitest.pyodide.config.ts b/vitest.pyodide.config.ts new file mode 100644 index 00000000..61c7ad89 --- /dev/null +++ b/vitest.pyodide.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: [ + 'test/runtime_pyodide_real.conformance.ts', + 'test/runtime_pyodide_browser.conformance.ts', + ], + testTimeout: 300_000, + }, +});