tywrap 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -15
- package/SECURITY.md +5 -6
- package/dist/core/generator.d.ts.map +1 -1
- package/dist/core/generator.js +11 -0
- package/dist/core/generator.js.map +1 -1
- package/dist/runtime/bridge-codec.d.ts +2 -2
- package/dist/runtime/bridge-codec.d.ts.map +1 -1
- package/dist/runtime/bridge-codec.js +51 -7
- package/dist/runtime/bridge-codec.js.map +1 -1
- package/dist/runtime/pyodide-bootstrap-core.generated.d.ts.map +1 -1
- package/dist/runtime/pyodide-bootstrap-core.generated.js +1 -1
- package/dist/runtime/pyodide-bootstrap-core.generated.js.map +1 -1
- package/dist/runtime/validators.d.ts +3 -2
- package/dist/runtime/validators.d.ts.map +1 -1
- package/dist/runtime/validators.js +9 -7
- package/dist/runtime/validators.js.map +1 -1
- package/dist/utils/codec.d.ts +16 -0
- package/dist/utils/codec.d.ts.map +1 -1
- package/dist/utils/codec.js +493 -78
- package/dist/utils/codec.js.map +1 -1
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +1 -1
- package/runtime/tywrap_bridge_core.py +394 -49
- package/src/core/generator.ts +15 -0
- package/src/runtime/bridge-codec.ts +64 -9
- package/src/runtime/pyodide-bootstrap-core.generated.ts +1 -1
- package/src/runtime/validators.ts +17 -9
- package/src/utils/codec.ts +743 -114
- package/src/version.ts +1 -1
|
@@ -10,7 +10,11 @@
|
|
|
10
10
|
|
|
11
11
|
import { BridgeCodecError, BridgeProtocolError, BridgeExecutionError } from './errors.js';
|
|
12
12
|
import { containsSpecialFloat } from './validators.js';
|
|
13
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
decodeValueAsync as decodeScientificValue,
|
|
15
|
+
isScientificMarker,
|
|
16
|
+
ScientificDecodeError,
|
|
17
|
+
} from '../utils/codec.js';
|
|
14
18
|
import { PROTOCOL_ID } from './transport.js';
|
|
15
19
|
|
|
16
20
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
@@ -77,6 +81,10 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
|
77
81
|
return proto === Object.prototype || proto === null;
|
|
78
82
|
}
|
|
79
83
|
|
|
84
|
+
function isPlainArray(value: unknown): value is unknown[] {
|
|
85
|
+
return Array.isArray(value) && Object.getPrototypeOf(value) === Array.prototype;
|
|
86
|
+
}
|
|
87
|
+
|
|
80
88
|
/**
|
|
81
89
|
* Build a path string for error messages.
|
|
82
90
|
*/
|
|
@@ -87,6 +95,29 @@ function buildPath(basePath: string, key: string | number): string {
|
|
|
87
95
|
return typeof key === 'number' ? `${basePath}[${key}]` : `${basePath}.${key}`;
|
|
88
96
|
}
|
|
89
97
|
|
|
98
|
+
function containsScientificEnvelope(value: unknown): boolean {
|
|
99
|
+
const pending: unknown[] = [value];
|
|
100
|
+
while (pending.length > 0) {
|
|
101
|
+
const current = pending.pop();
|
|
102
|
+
if (isPlainArray(current)) {
|
|
103
|
+
for (const item of current) {
|
|
104
|
+
pending.push(item);
|
|
105
|
+
}
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (!isPlainObject(current)) {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (typeof current.__tywrap__ === 'string') {
|
|
112
|
+
return isScientificMarker(current.__tywrap__);
|
|
113
|
+
}
|
|
114
|
+
for (const item of Object.values(current)) {
|
|
115
|
+
pending.push(item);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
|
|
90
121
|
/**
|
|
91
122
|
* Validate request-only restrictions in one traversal.
|
|
92
123
|
*
|
|
@@ -608,6 +639,13 @@ export class BridgeCodec {
|
|
|
608
639
|
decodeResponse<T>(payload: string): T {
|
|
609
640
|
const result = this.parseResponseResult(payload);
|
|
610
641
|
|
|
642
|
+
if (containsScientificEnvelope(result)) {
|
|
643
|
+
throw new BridgeCodecError('scientific envelopes require decodeResponseAsync', {
|
|
644
|
+
codecPhase: 'decode',
|
|
645
|
+
valueType: 'scientific-envelope',
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
|
|
611
649
|
// Post-decode validation for special floats if enabled
|
|
612
650
|
this.assertNoSpecialFloats(result);
|
|
613
651
|
|
|
@@ -615,8 +653,8 @@ export class BridgeCodec {
|
|
|
615
653
|
}
|
|
616
654
|
|
|
617
655
|
/**
|
|
618
|
-
* Async version that
|
|
619
|
-
* Use this when the response may contain encoded
|
|
656
|
+
* Async version that decodes scientific envelopes.
|
|
657
|
+
* Use this when the response may contain encoded scientific values.
|
|
620
658
|
*
|
|
621
659
|
* @param payload - The JSON string received from Python
|
|
622
660
|
* @returns Decoded and validated result with Arrow decoding applied
|
|
@@ -627,16 +665,33 @@ export class BridgeCodec {
|
|
|
627
665
|
async decodeResponseAsync<T>(payload: string): Promise<T> {
|
|
628
666
|
const result = this.parseResponseResult(payload);
|
|
629
667
|
|
|
630
|
-
//
|
|
668
|
+
// Decode scientific envelopes in the result.
|
|
631
669
|
let decoded: unknown;
|
|
632
670
|
try {
|
|
633
|
-
decoded = await
|
|
671
|
+
decoded = await decodeScientificValue(result);
|
|
634
672
|
} catch (err) {
|
|
635
673
|
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
674
|
+
const decodeError = err instanceof ScientificDecodeError ? err : undefined;
|
|
675
|
+
const marker =
|
|
676
|
+
decodeError?.marker ??
|
|
677
|
+
(isPlainObject(result) && isScientificMarker(result.__tywrap__)
|
|
678
|
+
? result.__tywrap__
|
|
679
|
+
: 'unknown');
|
|
680
|
+
const genuineArrowError = decodeError?.kind === 'arrow';
|
|
681
|
+
const valueType = genuineArrowError
|
|
682
|
+
? 'arrow'
|
|
683
|
+
: marker === 'unknown'
|
|
684
|
+
? 'scientific-envelope'
|
|
685
|
+
: marker;
|
|
686
|
+
throw new BridgeCodecError(
|
|
687
|
+
genuineArrowError
|
|
688
|
+
? `Arrow decoding failed: ${errorMessage}`
|
|
689
|
+
: `Scientific envelope decoding failed (${marker}): ${errorMessage}`,
|
|
690
|
+
{
|
|
691
|
+
codecPhase: 'decode',
|
|
692
|
+
valueType,
|
|
693
|
+
}
|
|
694
|
+
);
|
|
640
695
|
}
|
|
641
696
|
|
|
642
697
|
// Post-decode validation for special floats if enabled
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* Regenerate with: node scripts/generate-pyodide-bootstrap.mjs
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
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__': <type>,\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 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\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 (larger payloads, potential dtype loss).\"\"\"\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 }\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: records orientation.\"\"\"\n try:\n data = obj.to_dict(orient='records')\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for pandas.DataFrame') from exc\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 (potentially lossy dtype/NA representation).\"\"\"\n try:\n data = obj.to_list() # type: ignore\n except Exception:\n try:\n data = obj.to_dict() # type: ignore\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for pandas.Series') from exc\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 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 lossy-but-lossless device\n transfer and 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\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 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 try:\n arr = tensor.numpy()\n except Exception as exc:\n raise RuntimeError('Failed to convert torch.Tensor to numpy') from exc\n\n return {\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\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\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 The remaining BridgeCodec value behaviors (numpy/pandas scalars, bytes, sets,\n complex rejection, NaN/Infinity) are applied later during JSON encoding by\n default_encoder.\n \"\"\"\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 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 return serialize_dataframe(obj, force_json_markers=force_json_markers)\n if is_pandas_series(obj):\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 return serialize_sparse_matrix(obj)\n elif package == 'torch' and 'torch' in sys.modules:\n if is_torch_tensor(obj):\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 return serialize_sklearn_estimator(obj)\n\n if isinstance(obj, (type(None), bool, int, float, str, dict, list, tuple)):\n return obj\n\n pydantic_value = serialize_pydantic(obj)\n if pydantic_value is not _NO_PYDANTIC:\n return pydantic_value\n stdlib_value = serialize_stdlib(obj)\n if stdlib_value is not None:\n return stdlib_value\n return obj\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 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\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 if (\n 'nan' in error_msg\n or 'infinity' in error_msg\n or 'inf' in error_msg\n or 'out of range float' in error_msg\n ):\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";
|
|
12
|
+
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__': <type>,\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";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BridgeValidationError } from './errors.js';
|
|
2
|
+
import type { ScientificMarker } from '../utils/codec.js';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Pure validation functions for runtime value checking.
|
|
@@ -34,12 +35,17 @@ export type ReturnSchema =
|
|
|
34
35
|
}
|
|
35
36
|
| { kind: 'union'; options: ReturnSchema[] }
|
|
36
37
|
| { kind: 'ref'; name: string }
|
|
37
|
-
| {
|
|
38
|
+
| {
|
|
39
|
+
kind: 'marker';
|
|
40
|
+
marker: ScientificMarker;
|
|
41
|
+
dims?: number;
|
|
42
|
+
dtype?: string;
|
|
43
|
+
};
|
|
38
44
|
|
|
39
45
|
export type ReturnValidator<T = unknown> = (result: T) => T;
|
|
40
46
|
|
|
41
47
|
export interface DecodedShapeMetadata {
|
|
42
|
-
marker:
|
|
48
|
+
marker: ScientificMarker;
|
|
43
49
|
dims?: number;
|
|
44
50
|
dtype?: string;
|
|
45
51
|
}
|
|
@@ -66,13 +72,7 @@ export function describeReceivedShape(value: unknown): string {
|
|
|
66
72
|
if (value === undefined) {
|
|
67
73
|
return 'undefined';
|
|
68
74
|
}
|
|
69
|
-
if (value
|
|
70
|
-
return `Uint8Array(${value.byteLength})`;
|
|
71
|
-
}
|
|
72
|
-
if (Array.isArray(value)) {
|
|
73
|
-
return `array(${value.length})`;
|
|
74
|
-
}
|
|
75
|
-
if (typeof value === 'object') {
|
|
75
|
+
if (isObjectLike(value)) {
|
|
76
76
|
const marker = decodedShapeMetadata.get(value);
|
|
77
77
|
if (marker) {
|
|
78
78
|
const details = [marker.dims === undefined ? undefined : `${marker.dims}d`, marker.dtype]
|
|
@@ -80,6 +80,14 @@ export function describeReceivedShape(value: unknown): string {
|
|
|
80
80
|
.join(', ');
|
|
81
81
|
return `${marker.marker}${details ? ` (${details})` : ''}`;
|
|
82
82
|
}
|
|
83
|
+
}
|
|
84
|
+
if (value instanceof Uint8Array) {
|
|
85
|
+
return `Uint8Array(${value.byteLength})`;
|
|
86
|
+
}
|
|
87
|
+
if (Array.isArray(value)) {
|
|
88
|
+
return `array(${value.length})`;
|
|
89
|
+
}
|
|
90
|
+
if (typeof value === 'object') {
|
|
83
91
|
const name = (value as { constructor?: { name?: unknown } }).constructor?.name;
|
|
84
92
|
return typeof name === 'string' && name !== 'Object' ? name : 'object';
|
|
85
93
|
}
|